C语言计算文件大小

用fgetc方法

#include <stdio.h>

int main()
{
	FILE *fp;
	char ch;
	int num=0;
	fp=fopen("zi.tex","r");
	while ((ch=fgetc(fp))!=-1)
		num++;

	printf("%d\n",num); 
	fclose(fp);
}
用fgets方法

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
	FILE *fp;
	char str[100] = {0};
	int t = 0;

	if ((fp=fopen("zi.tex","r"))==NULL)
   	{
   		printf("Can' t open the zi.tex\n");
      		return -1;
	}
     
	if((fgets(str,100,fp)) == NULL)
	{
		printf("fgets fail\n");
		return -1;
     		//puts(str);
		//t++;
	}
	
	while(str[t] != 10)
		t++;
	t++;
	printf("t = %d\n",t);
	for(t = 0;t<100;t++)
		printf("%d	",str[t]);
	fclose(fp);
	 
	return 0;
}

用fread方法

#include <stdio.h>

int main()
{
	FILE *fp;
	char ch[100];
	size_t num=0;
	fp=fopen("zi.tex","r");
	num = fread(ch, sizeof(char),sizeof(ch), fp);

	printf("num = %d",num);
	return 0;
}

用read方法

#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
	int net,net1,net2,t;
	char buf[100] = {0};
	net = open("zi.tex",O_RDWR,0777);
	if(net < 0)
	{
		printf("open fail\n");
		return -1;
	}
	//lseek(net,0,2);
	net1 = read(net,buf,100);
	if(net1 < 0)
	{
		printf("read fail\n");
		return -1;
	}
	printf("net1 = %d\n",net1);
	printf("buf = %s\n",buf);
	close(net);
	
	return 0;
	
}

另外一些方法

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
	int fd_t;
	FILE *fd;
	struct stat buf;

//======== low level ============================================
	fd_t = open(argv[1], O_RDWR, 0666);
	if (fd_t < 0)
	{
		printf("fail to open the file\n");
		exit(1);
	}

	printf("size1 = %d\n", (int)lseek(fd_t, 0L, SEEK_END));//返回指针

	if (close(fd_t) == -1)
	{
		printf("fail to close the file\n");
		exit(1);
	}

//======= standard ==============================================
	fd = fopen(argv[1], "r");
	if (fd == NULL)
	{
		printf("fail to fopen the file\n");
		exit(1);
	}

	fseek(fd, 0L, SEEK_END);//指向末尾
	printf("size2 = %ld\n", ftell(fd));//

	if (fclose(fd) == EOF)
	{
		printf("fail to fclose the file\n");
		exit(1);
	}

//==============================================================
	if (stat(argv[1], &buf) != 0)//读取文件属性
	{
		printf("stat fail\n");
		exit(1);
	}
	printf("size3 = %d\n", (int)buf.st_size);


	return 0;
}
注意:用fgetc等,是把流指就到了最后,再给到fread(buf,sizeof(char),num,fp);就会读取不到。

而ftell和fseek结合一起来用的话,就可以让指针回到首地址,然后给fread用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值