温馨提示×

c++中ftell函数的用法是什么

c++
小樊
139
2024-08-15 06:13:39
栏目: 编程语言

在C++中,ftell函数用于获取文件当前位置的指针位置(以字节为单位)。其语法如下:

long int ftell(FILE *stream); 

其中,stream是指向要获取当前位置的文件的指针。ftell函数返回当前文件位置相对于文件开头的偏移量,如果出现错误,则返回-1。

以下是一个示例用法:

#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); // 打开文件 if (file == NULL) { perror("Error opening file"); return 1; } fseek(file, 0, SEEK_END); // 将文件指针定位到文件末尾 long int pos = ftell(file); // 获取当前文件指针位置 printf("Current position: %ld\n", pos); fclose(file); // 关闭文件 return 0; } 

注意,ftell函数返回的值类型为long int,因此需要使用%ld格式化符号打印。

0