Passion/Programming

[C] 한줄씩 파일에서 읽기

sunshout 2006. 10. 28. 16:31

#include < stdio.h >

void main()
{

   FILE *fp;

   char s[81];

   fp = fopen("input.txt", "r");  // 파일 열기

   while(!feof(fp))  // 파일의 끝이 아니라면

   {

       fgets(s, 80, fp);  // 최대 80칸짜리 한줄 읽기

       puts(s);  // 한줄 출력

   }

   fclose(fp);

}


Example 4:  Write a function that sums up integers from
a text file, one int per line.

#include <stdio.h>

#include <stdlib.h>


int main(int argc, char* argv[])

{

    FILE *fp;

    int score;

    int total=0;

    fp = fopen("score.txt", "r");

    if (fp == NULL) {

        fprintf(stderr, "Can't open file\n");

        exit(1);

    }

    int ret;

    while(!feof(fp))

    {

        if ( fscanf(fp, "%d", &score) == 1)

        {

            printf("Current score:%d\n", score);

            total = total + score;

        }

   }

    printf("Total:%d\n", total);

    fclose(fp);

    return 0;

}