问题
Part of Code 1:-
while(1)
{
ch=fgetc(pt);
if(c==EOF)
{
break;
}
if(c==' ')
{
fputc('z',pt);
}
}
Part of Code 2:-
while(1)
{
ch=fgetc(pt);
if(c==EOF)
{
break;
}
if(c==' ')
{
fseek(pt,0,SEEK_CUR);
fputc('z',pt);
fseek(pt,0,SEEK_CUR);
}
}
I want to replace next character after every space
in a file. That file is pointed by the pointer pt
.
Both the code shows no error and runs fine, but when I externally opens the .txt
file, first code did nothing whereas the second code replaces the next character after space
successfully.
Clearly fseek(pt,0,SEEK_CUR);
is making the difference.
So I am unable to understand that what it is doing in the second code?
回答1:
The use of fseek()
here - The C standard requires a positioning operation between a read and a write operation on an update stream, or between a write and a read. This is a positioning operation between a write and a read. It is not a no-op; it places the stream into a mode which allows the next fgetc()
to work correctly, reliably, across platforms, as required by the C standard.
EDIT:
2 fseek()
calls are required because the first one acts as the "no-op" call between an fgetc()
and a subsequent fputc()
call. After the fputc()
, the second one acts as the "no-op" between the fputc()
and the subsequent fgetc()
call. (since a loop is running)
来源:https://stackoverflow.com/questions/21965142/need-of-fseek-in-c