2026/08/08 C语言的文件标准io小练习
要求利用标准IO函数接口实现计算一个本地磁盘某个文件的大小,要求文件名称通过命令行进行传递,并进行验证是否正确。
方案1
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (2 != argc)
{
printf("argument is invaild\n");
exit(1);
}
FILE *fp = fopen (argv[1],"rb"); //以二进制方式打开文件
if (NULL == fp)
{
perror("open file error");
exit(1);
}
int cnt = 0;
while(1)
{
if(fgetc(fp) == EOF)
{
printf("end of file\n");
break;
}
cnt++;
}
printf("file[%s]: size = %d\n",argv[1],cnt );
return 0;
}
验证:

方案2
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (2 != argc)
{
printf("argument is invaild\n");
exit(1);
}
FILE *fp = fopen (argv[1],"ab"); //以二进制追加写入方式打开文件
if (NULL == fp)
{
perror("open file error");
exit(1);
}
printf("file[%s]: size = %ld\n",argv[1],ftell(fp)); //利用ftell函数直接计算
return 0;
}
验证:

作者:bbzhu04@gmail.com ,多有不妥之处,望批评指正
本文原创,欢迎转载;转载请在文章显著位置标明原文链接: href="https://www.cnblogs.com/zhubb/p/22342885"
保留所有权限,未经许可禁止篡改、商用发布。

浙公网安备 33010602011771号