#include <stdio.h> #include <errno.h> #include <string.h> int get_file_size(const char *file); int main(int argc, const char *argv[]) { if(argc < 2) { printf("no file name or path\n"); return -1; } else { printf("total %d bytes\n",get_file_size(argv[1])); } return 0; } 1、fgetc()获取文件大小 int get_file_size(const char *file) { int count=0; FILE *fp; if((fp = fopen(file,"r")) == NULL) { perror("fopen"); //printf("fopen:%s\n",strerror(errno));//errno-----<errno.h>,strerror()------<string.h> return -1; } while(fgetc(fp) != EOF) { count ++; } if((fclose(fp)) == EOF) { perror("fclose"); return EOF; } return count; } 运行结果 2、定位流获取文件大小fseek(),ftell() int get_file_size(const char *file) { int count; FILE *fp; if((fp = fopen(file,"r")) == NULL)//文件以只读模式打开时流的读写位置在文件开头。若打开模式是“a”追加,则读写位置在文件末尾 { perror("fopen"); return -1; } fseek(fp,0,SEEK_END);//将流的读写位置定位到文件末尾 count = ftell(fp);//读取流的当前读写位置 if((fclose(fp)) == EOF) { perror("fclose"); return EOF; } return count; } 运行结果