`ftell` — 현재 파일 위치 지시자를 읽는 함수
ftell — 현재 파일 위치 지시자를 읽는 함수
파일을 읽다 보면 "지금 어디쯤 읽고 있지?"가 궁금해질 때가 있어요. 그걸 알려 주는 함수가 ftell이에요. 아까 배운 fseek으로 되돌아갈 자리를 기억해 두는 용도로 특히 자주 쓰입니다.
본문
ftell은 파일 스트림 stream의 파일 위치 지시자를 돌려줘요.
문법
#include <stdio.h>
long ftell( FILE *stream );
설명
스트림이 이진(binary) 모드로 열려 있으면, 이 함수가 돌려주는 값은 파일의 시작에서부터의 바이트 수예요. 텍스트 모드로 열려 있으면 값은 특정되지 않으며, fseek()의 입력으로만 의미가 있습니다.
매개변수
| 매개변수 | 설명 |
|---|---|
stream |
조사할 파일 스트림 |
반환값
성공하면 파일 위치 지시자를 돌려주고, 실패하면 -1L을 돌려줘요. 오류가 나면 errno 변수에는 구현에 정의된 양수 값이 설정됩니다.
주의
Windows에서는 _ftelli64를 쓰면 2 GiB보다 큰 파일도 다룰 수 있어요.
예시
ftell()을 오류 검사와 함께 사용해, 파일에 몇 개의 부동소수점(FP) 값을 쓰고 읽으며 위치가 어떻게 움직이는지 보여 주는 예시예요.
#include <stdio.h>
#include <stdlib.h>
/* If the condition is not met then exit the program with error message. */
void check(_Bool condition, const char *func, int line)
{
if (condition)
return;
perror(func);
fprintf(stderr, "%s failed in file %s at line # %d\n", func, __FILE__, line - 1);
exit(EXIT_FAILURE);
}
int main(void)
{
/* Prepare an array of FP values. */
#define SIZE 5
double A[SIZE] = {1.1, 2.0, 3.0, 4.0, 5.0};
/* Write array to a file. */
const char *fname = "/tmp/test.bin";
FILE *file = fopen(fname, "wb");
check(file != NULL, "fopen()", __LINE__);
const int write_count = fwrite(A, sizeof(double), SIZE, file);
check(write_count == SIZE, "fwrite()", __LINE__);
fclose(file);
/* Read the FP values into array B. */
double B[SIZE];
file = fopen(fname, "rb");
check(file != NULL, "fopen()", __LINE__);
long int pos = ftell(file); /* position indicator at start of file */
check(pos != -1L, "ftell()", __LINE__);
printf("pos: %ld\n", pos);
const int read_count = fread(B, sizeof(double), 1, file); /* read one FP value */
check(read_count == 1, "fread()", __LINE__);
pos = ftell(file); /* position indicator after reading one FP value */
check(pos != -1L, "ftell()", __LINE__);
printf("pos: %ld\n", pos);
printf("B[0]: %.1f\n", B[0]); /* print one FP value */
return EXIT_SUCCESS;
}
가능한 출력:
pos: 0
pos: 8
B[0]: 1.1
시작 위치는 0이고, double 하나(8바이트)를 읽은 뒤에는 8이 되는 걸 볼 수 있어요. 이 값은 나중에 fseek의 SEEK_SET 오프셋으로 그대로 되돌려 쓸 수 있습니다.
더 알아보기
fgetpos— 파일 위치 지시자를 얻어요.fseek— 파일 위치 지시자를 파일의 특정 위치로 이동해요.fsetpos— 파일 위치 지시자를 파일의 특정 위치로 이동해요.- cppreference의 ftell 원문에서 표준 항목별 세부 규칙을 더 확인할 수 있어요.