C语言获取超大文件(超过2G)大小的功能
昨天在使用fseek及ftell获取大小超过2G的文件大小时发现ftell获取到的值为-1,即便其返回值类型定义为long long还是为-1.
经过查阅文档才发现,针对超大文件有新的函数可以获取文件大小。
fseeko64 和 ftello64两个方法结合就能得出文件正确的大小了。
使用方式如下:
off64_t getFileSize(char *filePath) {
FILE *f;
f = fopen(filePath, "rb");
if (NULL == f) {
printf("getFileSize fopen error\n");
return -1;
}
if (0 != fseeko64(f, 0, SEEK_END)) {
printf("getFileSize fseek error\n");
return -1;
}
off64_t fileSize = ftello64(f);
if (fileSize < 0) {
printf("ftell error\n");
}
printf("fileSize:%lld\n", fileSize);
fclose(f);
return fileSize;
}