#include<stdio.h>

main(void)
{
      int state;
      char buf[30];

      //file open
      FILE * file = fopen("c:\\test.txt", "wt");
      if(file == NULL){
            puts("file open error!");
            return 1;
      }

      //test.txt에 abcdefg12345를 입력.
      fputs("abcdefg12345", file);

      //file close
      state = fclose(file);
      if(state != 0){
            puts("file close error!");
            return 1;
      }

      //file open
      file = fopen("c:\\test.txt", "rt");
      if(file == NULL){
             puts("file open error!\n");
            return 1;
      }

      /* test.txt의 내용을 입력받아서 모니터에 출력. */
      fgets(buf, 7, file);         //7개만큼의 문자만 받아서 buf에 저장.
      puts(buf);//출력

      /* 파일 위치 지시자 이동 */
      fseek(file, 2, SEEK_CUR);         //현재 위치에서 +2만큼 간다.
      //fseek(file, -2, SEEK_CUR);         //현재 위치에서 -2만큼 간다.
      //fseek(file, 2, SEEK_SET);         //파일의 처음가서 +2만큼 간다.
      //fseek(file, -2, SEEK_END);         //파일의 끝으로 가서 -2만큼 간다.

      printf("%c \n", fgetc(file));         //파일 위치 지시자가 위치하고 있는 곳의 문자를 모니터에 출력.

      //file close
      state = fclose(file);
      if(state != 0){
            puts("file close error!\n");
            return 1;
      }

      return 0;
}


int fseek(FILE * stream, long offset, int wherefrom)
성공 시 0을, 실패 시 0이 아닌 값을 리턴.

stream이 가리키는 파일의 파일 위치 지시자를 시작 위치 wherefrom에서부터 offset 만큼 이동한다. 라고 이해하면 된다.

SEEK_SET(0) - 파일의 맨 앞으로 이동.
SEEK_CUR(1) - 이동하지 않음.
SEEK_END(2) - 파일의 끝으로 이동.

 SEEK_SET 과 rewind(file* stream)는 같음. 둘 다 파일위치 지시자 초기화.

참고로, "SEEK_END"의 이동하는 파일의 끝이란, 파일의 끝인 EOF를 의미한다.

Posted by scii
: