C获取文件大小

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <error.h>
 5 
 6 /*
 7 FILE *fopen(const char *filename, const char *mode);
 8 int fclose(FILE *stream);
 9 
10 size_t fread(void *buffer, size_t size, size_t count, FILE *stream);
11 size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
12 
13 int fseek(FILE *stream, long offset, int origin);
14 long ftell(FILE *stream);
15 
16 fseek()函数中origin可以取如下值:
17 SEEK_SET从文件的开始处开始搜索;
18 SEEK_CUR从当前位置开始搜索;
19 SEEK_END从文件的结束处开始搜索。
20 */
21 
22 int main(int arc, char* const argv[])
23 {
24     int theSize = 0;
25     FILE* fp = fopen("main.c", "r");
26     if (fp == NULL)
27         return -1;
28 
29     if (fseek(fp, 0, SEEK_END) < 0)
30         return -1;
31 
32     theSize = ftell(fp);  // 取得文件大小
33 
34     printf("The file size: %d byte!\n", theSize);
35 
36     fclose(fp);
37 
38     return 0;
39 }
40 

C和C++取得文件大小的方法差不多相同。


C语言:fseek()、ftell()。

C++语言:seekg()、tellg()。

原文地址:https://www.cnblogs.com/Robotke1/p/3038187.html