The read
part is the one that reverses the characters. Since each read
of 1 character moves the file position forward by one character, we must go backward 2 characters to advance backwards.
Suppose the file is only 2 characters long, having contents AB
:
AB
In the beginning in a part of the code you didn't show here, the file pointer is positioned one before the end of file, so it is pointing at B
.
|
v
AB
Now we read one character - B
is read. The file pointer on fdin
is advanced to the end of file.
|
v
AB
If we seek backwards by one character, we'll end up at B
again. But if we seek backwards 2 character, it will point to A
:
|
v
AB
And we end up reading first B
then A
.
Finally when we try to seek beyond the beginning of the file, lseek
will return (off_t)-1
to signify an error condition and the while
loop condition becomes false and the loop is exited.