Namespaces
Variants

std:: ftell

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

파일 스트림 stream 의 파일 위치 표시자 현재 값을 반환합니다.

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

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

목차

매개변수

stream - 검사할 파일 스트림

반환값

성공 시 파일 위치 표시자 또는 - 1L 실패 시 반환됩니다. 또한 실패 시 errno 를 설정합니다.

참고 사항

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

예제

std::ftell() 의 오류 검사 기능을 보여줍니다. 몇 개의 부동 소수점(FP) 값을 파일에 쓰고 읽습니다.

#include <cstdio>
#include <cstdlib>
#include <iostream>
// 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;
    std::perror(func);
    std::cerr << func << " failed in file " << __FILE__ << " at line # " << line - 1
              << '\n';
    std::exit(EXIT_FAILURE);
}
int main()
{
    // Prepare an array of FP values.
    constexpr int SIZE {5};
    double A[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5};
    // Write array to a file.
    const char* fname = "/tmp/test.bin";
    FILE* file = std::fopen(fname, "wb");
    check(file != NULL, "fopen()", __LINE__);
    const int write_count = std::fwrite(A, sizeof(double), SIZE, file);
    check(write_count == SIZE, "fwrite()", __LINE__);
    std::fclose(file);
    // Read the FP values into array B.
    double B[SIZE];
    file = std::fopen(fname, "rb");
    check(file != NULL, "fopen()", __LINE__);
    long pos = std::ftell(file); // position indicator at start of file
    check(pos != -1L, "ftell()", __LINE__);
    std::cout << "pos: " << pos << '\n';
    const int read_count = std::fread(B, sizeof(double), 1, file); // read one FP value
    check(read_count == 1, "fread()", __LINE__);
    pos = std::ftell(file); // position indicator after reading one FP value
    check(pos != -1L, "ftell()", __LINE__);
    std::cout << "pos: " << pos << '\n';
    std::cout << "B[0]: " << B[0] << '\n'; // print one FP value
    return EXIT_SUCCESS;
}

가능한 출력:

pos: 0
pos: 8
B[0]: 1.1

참고 항목

파일 위치 표시자를 얻음
(함수)
파일 내 특정 위치로 파일 위치 표시자를 이동
(함수)
파일 내 특정 위치로 파일 위치 표시자를 이동
(함수)
입력 위치 표시자를 반환
( std::basic_istream<CharT,Traits> 의 public 멤버 함수)
출력 위치 표시자를 반환
( std::basic_ostream<CharT,Traits> 의 public 멤버 함수)