#include <stdio.h>
#include <stdlib.h>
int main (int argc,char *argv[])
{
int ch;
long count=0;
FILE *fp;
if (argc!=2)
{
printf("请输入一个参数\n");
exit(1);
}
if ((fp=fopen("write.txt","r"))==NULL)
{
printf("不能打开这个文件\n");
exit(2);
}
while((ch=getc(fp))!=EOF)
{
putc(ch,stdout);
count++;
}
printf("\n共有%d个文字\n",count);
while((ch=getc(fp))!=‘\n‘)
{
putc(ch,stdout);
}
fclose(fp);
return 0;
}程序运行后一直循环输出同一个非字母字符。
原因:
fopen返回一个文件指针,运行完 while((ch=getc(fp))!=EOF)语句后,fp指针此时的位置在文件未
造成while((ch=getc(fp))!=‘\n‘)一直为真,所以一直循环
在 while((ch=getc(fp))!=‘\n‘)前加入
fseek(fp,0L,SEEK_SET);
即可
同时count所显示的字数比write.txt文件中的字符数要多,可见putc读取了‘\n’;
问题:如果我需要改变文本文件中字符为连续文本,是否可以空白字符代替‘\n’
如果要读取文本文件中的某一行并输出这一行的内容如何操作。
while((ch=getc(fp))!=EOF)
{
while(ch==‘\n‘)
count++;
if ((count==3)&&(ch!=‘\n‘))//输出第四行内容并在遇到第四行回车符时停止循环
putc(ch,stdout);
}
这样是否可行是否有更好的办法?原文地址:http://cyuyanstudy.blog.51cto.com/2374172/1638129