库函数 ftell() 可用于获取文件当前的读写位置偏移量。
#include <stdio.h>
long ftell(FILE *stream);
参数 stream 指向对应的文件,函数调用成功将返回当前读写位置偏移量;调用失败将返回 -1 ,并会设置 errno 以指示错误原因。
示例代码:使用 fseek()和 ftell()函数获取文件大小
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = NULL;
int ret;
/* 打开文件 */
if (NULL == (fp = fopen("test.txt", "r")))
{
perror("fopen error");
exit(-1);
}
printf("文件打开成功!\n");
/* 将读写位置移动到文件末尾 */
if (0 > fseek(fp, 0, SEEK_END))
{
perror("fseek error");
fclose(fp);
exit(-1);
}
/* 获取当前位置偏移量 */
if (0 > (ret = ftell(fp)))
{
perror("ftell error");
fclose(fp);
exit(-1);
}
printf("文件大小: %d 个字节\n", ret);
/* 关闭文件 */
fclose(fp);
exit(0);
}
首先打开当前目录下的 test.txt 文件,将文件的读写位置移动到文件末尾,然后再获取当前的位置偏移量,也就得到了整个文件的大小。
运行结果如下: