📜  C++ ftell()(1)

📅  最后修改于: 2023-12-03 14:39:49.754000             🧑  作者: Mango

C++ ftell()

Introduction

ftell() is a function in C++ which is used to get the current position of the file pointer for the specified file. It is part of the C standard library cstdio and is commonly used for file handling operations.

Syntax

The syntax of ftell() function is:

long ftell(FILE *stream);
  • stream: A pointer to the FILE object that represents the file.
Return Value

The ftell() function returns the current offset (in bytes) from the beginning of the file associated with the FILE pointer. If an error occurs, it returns -1L.

Example

Let's see an example of how to use ftell() function in C++:

#include <cstdio>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == nullptr) {
        printf("Failed to open the file.");
        return 1;
    }
    
    // Move the file pointer to the end of the file
    fseek(file, 0, SEEK_END);
    
    // Get the current position of the file pointer
    long position = ftell(file);
    
    printf("Current position: %ld\n", position);
    
    fclose(file);
    return 0;
}

In this example, we open a file named "example.txt" in read mode and then move the file pointer to the end of the file using fseek() function. Finally, we use ftell() to get the current position of the file pointer and print it.

Notes
  • The file should be opened in binary mode ("rb" or "wb") when using ftell() and fseek() functions to handle binary files.
  • The initial position of the file pointer is 0 (beginning of the file).
  • The returned value of ftell() is of type long, so the format specifier %ld is used for printing it.

For more information, you can refer to the C++ reference.