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

//获取文件大小的三种方式
//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;
}	
	

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值