我在研究输入/输出文件。下面的代码涉及到一些函数,如:fgetc(),fgets(),fputs()。我不知道为什么它不能像我想要的那样工作。非常感谢你!下面是我的代码:为什么输入“abc !!!”但输出不是“abC+++”?
#include <stdio.h>
int main()
{
FILE *fp; //FILE type pointer
int c; //using to get each character from file
char buffer [256]; //array as buffer to archive string
fp = fopen("file.txt", "r"); /*open a file with only read mode*/
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}
while(!feof(fp)) /*check if has not yet reached to end of file*/
{
c = getc (fp); //get a character from fp
if(c == '!')
{
ungetc ('+', fp); //replace '!' by '+'
}
else
{
ungetc(c, fp); //no change
}
fgets(buffer,255,fp);//push string of fp to buffer
fputs(buffer, stdout); //outputting string from buffer to stdout
}
return(0);
}
有关如何进行读取循环的提示,请参阅http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong –