C 库 - ftell() 函数



C 库的 ftell() 函数返回给定流的当前文件位置。此函数对于确定文件中的下一个读或写操作将发生的位置非常重要。

语法

以下是 C 库 ftell() 函数的语法:

long ftell(FILE *stream);

参数

stream : 指向 FILE 对象的指针,指定文件流。FILE 对象通常通过使用 fopen() 函数获得。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

成功时,ftell() 返回当前文件位置作为长整数。失败时,它返回 -1L 并设置全局变量 errno 以指示错误。

示例 1

ftell() 的基本用法

在此示例中,我们打开一个文件,移动文件位置指示器,然后使用 ftell() 获取当前位置。

#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } // Move the file position indicator to the 10th byte fseek(file, 10, SEEK_SET); // Get the current position long position = ftell(file); if (position == -1L) { perror("ftell failed"); } else { printf("Current file position: %ld\n", position); } fclose(file); return 0; }

输出

以上代码产生以下结果:

Current file position: 10

示例 2

使用 ftell() 确定文件长度

此示例演示如何使用 ftell() 通过查找文件末尾来查找文件的长度。

#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } // Move the file position indicator to the end of the file fseek(file, 0, SEEK_END); // Get the current position, which is the file size long fileSize = ftell(file); if (fileSize == -1L) { perror("ftell failed"); } else { printf("File size: %ld bytes\n", fileSize); } fclose(file); return 0; }

输出

执行以上代码后,我们得到以下结果:

File size: 150 bytes
广告