c中的feof错误循环
我使用下面的代码从文件中读取一个字符并将其替换为另一个字符, 但我在转到文件末尾时遇到了 error.loop 。
怎么了?
我在 Linux(netbeans IDE)上测试了这段代码,它是正确的并且工作得很好,但是当我尝试在 Windows 中使用 VS 2008 时,我发现了一个非结束循环。
//address = test.txt
FILE *fp;
fp=fopen(address,"r+");
if(fp == 0)
{
printf("can not find!!");
}
else
{
char w = '0'; /// EDIT : int w;
while(1)
{
if((w = fgetc(fp)) != EOF)
{
if((w = fgetc(fp)) != EOF)
{
fseek(fp,-2,SEEK_CUR);
fprintf(fp,"0");
}
}
else
{
break;
}
}
}
fclose(fp);
I use below code to read a char from file and replace it with another,
but I have an error.loop in going to end of file.
What is wrong?
I tested this code on linux (netbeans IDE) and it was correct and worked beautiful but when I tried to use VS 2008 in windows , I found a non end loop.
//address = test.txt
FILE *fp;
fp=fopen(address,"r+");
if(fp == 0)
{
printf("can not find!!");
}
else
{
char w = '0'; /// EDIT : int w;
while(1)
{
if((w = fgetc(fp)) != EOF)
{
if((w = fgetc(fp)) != EOF)
{
fseek(fp,-2,SEEK_CUR);
fprintf(fp,"0");
}
}
else
{
break;
}
}
}
fclose(fp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将
fgetc
的结果存储在一个 char,而不是一个 int。顺便说一下,C FAQ中提到了这个问题。
编辑
再次阅读您的问题,您查找两个字符并写一个字符的方式非常可疑。这很可能导致无限循环。
EDIT2
你(可能)想要这样的东西(未经测试):
You are storing the result of
fgetc
in a char, instead of an int.Incidentally, this problem is mentioned in the C FAQ.
EDIT
Reading your question again, it's highly fishy the way you seek back two characters and write one character. That could well lead to an infinite loop.
EDIT2
You (likely) want something like this (untested):
cplusplus.com 上的 fopen 文档 说:
我们可以在
fprintf
之后添加一个fflush
调用来满足该要求。这是我的工作代码。它创建一个名为
example.txt
的文件,程序退出后该文件的内容将为000000000000n
。这是在 Windows 中使用 MinGW 进行测试的。
The fopen documentation on cplusplus.com says:
We can add an
fflush
call after thefprintf
to satisfy that requirement.Here is my working code. It creates a file named
example.txt
and after the program exits that file's contents will be000000000000n
.This was tested with MinGW in Windows.