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?
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 nextfgetc()
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 anfgetc()
and a subsequentfputc()
call. After thefputc()
, the second one acts as the "no-op" between thefputc()
and the subsequentfgetc()
call. (since a loop is running)