//获取文件大小的三种方式
//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)
{
//方法a
FILE * 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);
//方法b
int 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);
//方法c
struct stat buf;
//获取文件信息参数
res = fstat(fd, &buf);
if(-1 == res)
{
perror("FSTAT ERROR");
exit(1);
}
printf("文件的大小为:%ld\n", buf.st_size);
close(fd);
return 0;
}
c 到 unix c 高级编程中计算文件大小的三种方法
最新推荐文章于 2024-04-03 15:58:19 发布