본문 바로가기
공부,일/c언어

랜덤 액세스 :fseek(),ftell()

by fromnothing1 2021. 6. 7.

fseek()

int fseek(FILE *fp, long offse , int whence);

 

fp : 대상이 되는 파일 포인터 

offset: whence  위치부터 새로운 위치까지 상대적으로 떨어진 거리(바이트수)

whence: 파일 포인터 이동을 위한 기준점 

 

출처https://modoocode.com/72

 

C 언어 레퍼런스 - fseek 함수

 

modoocode.com

 

학생 socre 를 입력 받아서 저장하고

출력 하는 코드

#include<stdio.h>

int add();
int search();

typedef struct score
{
	int  eng, math;
	char name[20];
} STUCENT_SCORE;
char* fname = "result.dat";

int main()
{

	int stop = 0;
	do
	{
		printf("\n ======== wich fob do you want ?\n");
		printf("1. add\n");
		printf("2. search\n");
		printf("3. Quit\n");
		printf("\n  select menu : \n");

		switch (getche())
		{
		case '1': add();
			break;
		case '2': search();
			break;
		case '3': stop=1;
			break;
		default:
			break;
		}
	} while (!stop);
	return 0;

}

int add()
{
	int cnt1 = 0;
	int cnt2 = 0;
	FILE* fp;
	STUCENT_SCORE s;
	
	if (0 != fopen_s(&fp, fname, "ab+")) // 추가전용 모드로 이진파일 open
	{
		printf("File Open Error\n");
		exit(1);
	}

	printf("\n please , input data eng ,math, name");
	cnt1 = scanf_s("%d %d", &s.eng, &s.math); // Ctrl z 3 번 눌러야  eof return
	if (cnt1 = !2 || cnt1 == EOF)
	{
		return 0;
	}
	cnt2 = scanf_s("%s", s.name, 20);
	if (cnt2 = !1 || cnt2 == EOF)
	{
		return 0;
	}
	fseek(fp, 0L, SEEK_END); // 파일 끝으로 파일 포인터 옮김
	fwrite(&s, sizeof(STUCENT_SCORE), 1, fp);
	fflush(stdin);
	fclose(fp);
	return 1;

}

int search()
{
	int n ,cnt;
	STUCENT_SCORE s;
	FILE* fp;
	printf("\n Enter a student number :");
	scanf_s("%d",&n,4);
	printf("%d\n", n);
	if (0 != fopen_s(&fp, fname, "rb")) // 읽기 모드로 파일 열기 
	{
		printf("File Open Error\n");
		exit(1);
	}

	fseek(fp, (n - 1)*sizeof(STUCENT_SCORE), SEEK_SET);
	cnt = fread(&s, sizeof(STUCENT_SCORE), 1, fp);// 1블럭 만큼 읽어 들인다.
	if (cnt ==0 || cnt == EOF)
	{
		return 0;
	}
	printf("%d %d %s", s.eng, s.math, s.name);
	fclose(fp);
	return 1;

}

ftell 함수 

long ftell(FILE *fp);

: 파일 포인터의 위치를 얻어온다.

파일의 첫 시작 위치부터 현재 위치까지의 byte 수를 출력한다. 

오류 발생시 -1 return 

siaeof(STUCENT_SCORE) = 28

따라서 파읽을 읽은후 ftell 의 값은 28 씩 증가한다.

#include<stdio.h>



typedef struct score
{
	int  eng, math;
	char name[20];
} STUCENT_SCORE;
char* fname = "result.dat";

int main()
{

	int n, cnt;
	STUCENT_SCORE s;
	FILE* fp;

	if (0 != fopen_s(&fp, fname, "rb")) // 읽기 모드로 파일 열기 
	{
		printf("File Open Error\n");
		exit(1);
	}



	for (size_t i = 0; i < 3; i++)
	{
		fseek(fp, i * sizeof(STUCENT_SCORE), SEEK_SET);
		cnt = fread(&s, sizeof(STUCENT_SCORE), 1, fp);// 1블럭 만큼 읽어 들인다.
		if (cnt == 0 || cnt == EOF)
		{
			return 0;
		}
		printf("%d %d %s\n", s.eng, s.math, s.name);
		printf("ftell(fp) :%ld\n", ftell(fp));
	}
	fseek(fp, 0l, SEEK_END);
	printf("ftell(fp) :%ld\n", ftell(fp)); // 마지막 파일 위치 
	fclose(fp);
	return 0;
}

 

기타 파일 처리 함수 

void rewind(FILE *fp : 파일 포인터  위치를 파일 시작 위치로 옮긴다. 

int fflush(FILE *fp): 파일 버퍼를 비운다. 

'공부,일 > c언어' 카테고리의 다른 글

signed Vs unsigned  (0) 2021.06.13
c 언어 공부 추천 블로그  (0) 2021.06.09
파일 입출력  (0) 2021.06.06
구조체의 padding  (0) 2021.06.04
공용체  (0) 2021.06.04

댓글