Namespaces
Variants

ftell

From cppreference.net
< c ‎ | io
헤더 파일에 정의됨 <stdio.h>
long ftell ( FILE * stream ) ;

파일 스트림 stream 에 대한 파일 위치 표시자를 반환합니다.

스트림이 바이너리 모드로 열려 있는 경우, 이 함수로 얻은 값은 파일 시작부터의 바이트 수입니다.

스트림이 텍스트 모드로 열려 있는 경우, 이 함수가 반환하는 값은 지정되지 않으며 오직 fseek() 의 입력으로만 의미가 있습니다.

목차

매개변수

stream - 검사할 파일 스트림

반환값

성공 시 파일 위치 표시자 또는 - 1L 실패 시 반환됩니다.

오류 발생 시, errno 변수가 구현 정의된 양수 값으로 설정됩니다.

참고 사항

Windows에서, _ftelli64 함수를 사용하여 2GiB보다 큰 파일을 처리할 수 있습니다.

예제

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

참조문헌

  • C23 표준 (ISO/IEC 9899:2024):
  • 7.21.9.4 ftell 함수 (p: TBD)
  • C17 표준 (ISO/IEC 9899:2018):
  • 7.21.9.4 ftell 함수 (p: TBD)
  • C11 표준 (ISO/IEC 9899:2011):
  • 7.21.9.4 ftell 함수 (p: 337-338)
  • C99 표준 (ISO/IEC 9899:1999):
  • 7.19.9.4 ftell 함수 (p: 303-304)
  • C89/C90 표준 (ISO/IEC 9899:1990):
  • 4.9.9.4 ftell 함수

참고 항목

파일 위치 표시자를 얻음
(함수)
파일 위치 표시자를 파일 내 특정 위치로 이동
(함수)
파일 위치 표시자를 파일 내 특정 위치로 이동
(함수)