1

Why is it -2 and not -1? This is a part of a code that has to write a string from a file to another in reverse. Can you help me understand why it is -2 and not -1?

  while ( n >= 0)  {
       read(fdin, &c, 1);
       write(fdout, &c, 1);
       n=lseek(fdin,-2,SEEK_CUR);
  }

1 Answers1

3

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.