1.使用命令行传参及fgets函数统计文件大小
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ERR_MSG(msg){printf("line:%d\n",__LINE__);perror(msg);}
//统计文件大小函数
int size_file(char *argv)
{
int count=0;
char str[128]="";
//打开文件并判断
FILE *fp=fopen(argv,"r");
if(NULL==fp)
{
ERR_MSG("fopen");
return -1;
}
//循环统计文件大小
while(fgets(str,sizeof(str),fp)!=NULL) //循环终止条件
{
count+=strlen(str); //统计每一行字符串的大小
bzero(str,sizeof(str)); //清零承接数组
}
//关闭文件
if(fclose(fp)<0)
{
ERR_MSG("fclose");
return -1;
}
return count;
}
int main(int argc, const char *argv[])
{
//判断命令行函数输入参数
if(2==argc) //正确执行函数调用
{
int count=size_file(argv[1]);
//对返回值进行判断
if(count>0)
{
fprintf(stdout,"文件%s的大小为%d\n",argv[1],count);
return 0;
}else
{
printf("被调函数运行失败!\n");
return -1;
}
}else //失败错误提醒
{
printf("命令行参数输入错误!\n");
return -1;
}
}
使用命令行传参及fgets函数统计文件行数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ERR_MSG(msg){printf("line:%d\n",__LINE__);perror(msg);}
int line_file(char *argv)
{
int count=0;
char str[64]="";
//打开文件并判断
FILE *fp=fopen(argv,"r");
if(NULL==fp)
{
ERR_MSG("fopen");
return -1;
}
//循环统计文件行数
while(fgets(str,sizeof(str),fp)!=NULL) //循环终止条件
{
count++;
bzero(str,sizeof(str)); //清空承接数组
}
//关闭文件
if(fclose(fp)<0)
{
ERR_MSG("fclose");
return -1;
}
return count;
}
/*****************主函数******************/
int main(int argc, const char *argv[])
{
//判断命令行参数输入情况
if(2==argc)
{
int count =line_file(argv[1]); //正确调用统计行数函数
//对返回值进行判断
if(count>0)
{
printf("%s的行数为%d\n",argv[1],count);
return 0;
}else
{
printf("被调函数执行失败!\n");
return -1;
}
}else
{
printf("命令行参数输入有误!\n");
return -1;
}
}