This is my code. read a line and change it.
char buf[SIZE];
while (fgets(buf,SIZE,fp) != NULL)
{
to_upper(buf);
fseek(fp,-1L,SEEK_CUR);
fputs(buf,fp);
fseek(fp,1L,SEEK_CUR);
}
I know that I can create another file to implement, I want to konw why the code doesn't work?
As I noted in a comment, you need to capture the current read position before calling
fgets(); then you reset that position and write the revised data, and you need a seek of some sort after the write so that you can read again.The error checking after the open succeeds is non-existent, but the checking before that is crucial to safe operation.
The C standard §7.21.5.3 The
fopenfunction ¶7 says:The code shown is careful to use the 'no-op'
fseek(fp, 0, SEEK_CUR)call after the write and before the next read.