fseek()描述
C 库函数 int fseek(FILE *stream, long int offset, int whence) 设置流 stream 的文件位置为给定的偏移 offset,参数 offset 意味着从给定的 whence 位置查找的字节数。
下面是 fseek() 函数的声明。
int fseek(FILE *stream, long int offset, int whence)
参数
stream -- 这是指向 FILE 对象的指针,该 FILE 对象标识了流。 offset -- 这是相对 whence 的偏移量,以字节为单位。 whence -- 这是表示开始添加偏移 offset 的位置。它一般指定为下列常量之一: 常量 描述 SEEK_SET 文件的开头 SEEK_CUR 文件指针的当前位置 SEEK_END 文件的末尾
ftell()描述
C 库函数 long int ftell(FILE *stream) 返回给定流 stream 的当前文件位置。
下面是 ftell() 函数的声明。
long int ftell(FILE *stream)
参数
stream -- 这是指向 FILE 对象的指针,该 FILE 对象标识了流。
返回值
该函数返回位置标识符的当前值。如果发生错误,则返回 -1L,全局变量 errno 被设置为一个正值。
本文主要使用移动文件指针的方法计算文件大小,思路比较简单。
注意:C语言数字后面加下列字母
U 表示该常数用无符号整型方式存储,相当于 unsigned int L 表示该常数用长整型方式存储,相当于 long F 表示该常数用浮点方式存储,相当于 float
文件大小的变量类型,视情况而定,本文使用的unsigned int;实际应用中,文件过大时,这个变量可能会装不下。
#include#include #include unsigned int getFileSize(const char* filepath); int main(void) { unsigned int f_size = 0; f_size = getFileSize("./test.txt"); printf("get file size :%dn", f_size); return 0; } unsigned int getFileSize(const char* filepath) { static unsigned int file_size = 0; FILE* fp_r = fopen(filepath, "r"); if(NULL == fp_r) { printf("error :fail to open %sn", filepath); return file_size = 0; } // get file size by move pointer, unit byte fseek(fp_r, 0, SEEK_SET); fseek(fp_r, 0, SEEK_END); file_size = ftell(fp_r); fseek(fp_r, 0, SEEK_SET); fclose(fp_r); return file_size; }
参考资料:
https://www.w3cschool.cn/c/c-function-fseek.html
https://www.w3cschool.cn/c/c-function-ftell.html



