티스토리 뷰

Back-end/Spring Framework

파일 포지션

jhkang-dev 2019. 12. 22. 11:46

안녕하세요 강정호입니다.

 

오늘은 파일 포지션에 대해서 공부해보겠습니다.

 

파일 포지션 : 파일 내용을 다룰 때, 어떤 Operation을 수행하는 위치.

                 ex) 현재 반짝이는 커서가 어디에 있는지.

 

 

파일 오프셋 : 파일의 시작지점부터 현재 커서의 위치까지 얼마나 떨어져 있는지 정수로 보여주는 것이 offset 값이다.

 

ftell 함수에 현재 살아있는 file 포인터를 인자로 넣어서 함수를 호출하면 long 타입으로 offset을 반환한다.

 

아래 설명에 나타나 있듯이 fseek()는 파일의 포지션을 변경할 수 있는 함수이다.

1) fseek(fp, 5, SEEK_SET) : 파일의 시작지점부터 5칸을 건너뛰고 6칸부터 파일포지션을 위치시킴.

2) fseek(fp, 5, SEEK_CUR) : 현재 파일 포지션에서 5칸을 건너뛴 후에 파일 포지션을 위치시킴.

3) fseek(fp, -5, SEEK_END) : 파일의 끝에서부터 5칸을 건너뛴 후 파일 포지션을 위치시킴.

 

 

#include <stdio.h>
#include <string.h>
static int create_file(void) {
	FILE *fp;
	if (!(fp = fopen("datafile", "w"))) {
		printf("fopen() fail\n");
		return -1;
	}
	printf("After fopen(). offset = %ld\n", ftell(fp));
	fputs("hello world\n", fp);
	fputs("hello world2\n", fp);
	fputs("hello world3\n", fp);
	fputs("hello world4\n", fp);
	fputs("hello world5\n", fp);
	printf("Before fclose(). offset = %ld\n"), ftell(fp);
	printf("------------------------------------------------\n");
	fclose(fp);
	return 0;
}
static int read_file(void) {
	FILE *fp;
	char buf[1024];
	if (!(fp = fopen("datafile", "r+"))) {
		printf("fopen() fail\n");
		return -1;
	}
	printf("After fopen(). offset = %ld\n", ftell(fp));
	memset(buf, 0, sizeof(buf));
	fgets(buf, sizeof(buf), fp);
	printf("After fgets(). offset = %ld\n", ftell(fp));
	fseek(fp, 0, SEEK_END);
	printf("After fseek(). offset = %ld\n", ftell(fp));
	fputs("final\n", fp);
	printf("before fclose(). offsets = %ld\n", ftell(fp));
	printf("------------------------------------------------\n");
	fclose(fp);
	return 0;
}
int main(int argc, char **argv) {
	create_file();
	read_file();
	return 0;
}

[실행결과]

create_file(void)

  1. fputs("hello world\n", fp);  --> 12bytle(개행문자 \n 까지 포함)

  2. fputs("hello world2\n", fp); -- > 13byte

  3. fputs("hello world3\n", fp);  --> 13byte

  4. fputs("hello world4\n", fp); --> 13 byte

  5. fputs("hello world5\n", fp); --> 13 byte

 

12 + 13 + 13 + 13 + 13 = 64byte.

 

read_file(void)

fseek() 를 이용해서 SEEK_END 파일 포지션을 파일의 맨 끝에 놓고, 거기에 final 문자열을 추가하여 64바이트에서 70바이트가 된 것이다.

 

이상으로 파일 포지션에 대해 다루어봤습니다.

댓글