编写一个程序,统计一个文本文件的行数(C语言)

来源:百度知道 编辑:UC知道 时间:2024/05/21 19:47:19
编写一个程序,统计一个文本文件的行数.输入文件的文件名作为命令行参数的传入,输出文件名为stdout,内容包括输入文件中的每一行文本,并且在每一行前加上行号和一个空格.

#include<stdio.h>
main()
{FILE *fp,*fp1;
int cap=0, i=1;
char mid,filename[10];
printf("Input the filename like *.txt!\n");
scanf("%s",filename);
if((fp=fopen(filename,"r"))==NULL)
{printf("Can not open the file!\n");
exit (0);
}
if((fp1=fopen("stdout.txt","w+"))==NULL)
{printf("Can not open the file!\n");
exit (0);
}
while(!feof(fp))
{
mid=fgetc(fp);
if(mid=='\n') cap++;
}
fclose(fp);
if((fp=fopen(filename,"r"))==NULL)
{printf("Can not open the file!\n");
exit (0);
}
fprintf(fp1,"%d ",i++);
while(!feof(fp))
{
if(fputc(fgetc(fp),fp1)=='\n')
fprintf(fp1,"%d ",i++);
}
printf("cap=%d \n",cap+1);
fcl