'fscanf'에 해당되는 글 1건

  1. 2013.02.15 fprintf, fscanf함수를 이용한 구구단 프로그램

#include<stdio.h>

main()
{
       char c1, c2;
       int state;
       int i,j;
       int a, b, c;

       /* 파일의 개방 */
       FILE* file = fopen("c:\\test.txt", "wt");
       if(file == NULL)
       {
              printf("file open error!\n");
              return 1;
       }

       //fprintf 함수를 이용하여 test.txt에다가 구구단을 쓰게 함.
       for(i=2; i<10; i++)
              for(j=1; j<10; j++)
                     fprintf(file, "%d * %d = %d\n", i, j, i*j);

       /* 파일의 종결 */
       state = fclose(file);
       if(state != 0)
       {
              printf("file close error!\n");
              return 1;
       }

       /* 파일의 개방 */
       file = fopen("c:\\test.txt", "rt");
       if(file == NULL)
       {
              printf("file open errer!\n");
              return 1;
       }

       // fscanf 함수를 이용하여 test.txt의 내용을 a,c1,b,c2,c에 받아옴.
       for(i=2; i<10; i++)
       {
              for(j=1; j<10; j++)
              {
                     fscanf(file, "%d %c %d %c %d", &a, &c1, &b, &c2, &c); //file의 내용을 받아서.
                     fprintf(stdout, "%d %c %d %c %d\n", a, c1, b, c2, c); //모니터로 출력.
              }
       }

       /* 파일의 종결 */
        state = fclose(file);
       if(state != 0)
       {
              printf("file close error\n");
              return 1;
       }
        return 0;
}


       - fprintf와 fscanf의 형식 -

fprintf(FILE* stream, const char* format, ...)
fscanf(FILE* stream, const char* format, ...)

일반적으로 데이터 입력, 출력의 형식은 일치해야한다.!!!

그리고, 파일을 스무번 개방하면 스무번 모두 꼭 필히 닫아줘야 한다.

Posted by scii
: