c 到 unix c 高级编程中计算文件大小的三种方法

来源:互联网 发布:网络用语哔哔什么意思 编辑:程序博客网 时间:2024/05/17 01:41
//获取文件大小的三种方式//a、使用fseek函数调整到文件末尾,使用ftell函数大小//b、使用lseek函数调整到文件末尾,此时返回值的文件大小//c、使用stat/fstat函数获取,成员函数st_size是文件的大小#include <stdio.h>#include <stdlib.h>#include <sys/stat.h>#include <sys/types.h>#include <fcntl.h>#include <unistd.h>int main(void){//方法aFILE * fp = fopen("a.txt", "rb");if(NULL == fp){perror("FOPEN ERROR");exit(1);}//将文件指针移动到文件末尾fseek(fp, 0, SEEK_END);//使用ftell返回文件当前指针位置到文件头的偏移量int res = ftell(fp);printf("文件的大小为:%d\n", res);fclose(fp);//方法bint fd = open("a.txt", O_RDONLY);if(-1 == fd){perror("OPEN ERROR");exit(1);}res = 0;//从文件头偏移到文件尾,lseek返回的偏移量就是文件大小res = lseek(fd, 0, SEEK_END);printf("文件的大小为:%d\n", res);//方法cstruct stat buf;//获取文件信息参数res = fstat(fd, &buf);if(-1 == res){perror("FSTAT ERROR");exit(1);}printf("文件的大小为:%ld\n", buf.st_size);close(fd);return 0;}

1 0
原创粉丝点击