lseek(fd, 100, SEEK_END) moves the position 100 bytes "past the end" of a file. What happens if we read and write data after the end of a file?

Viewed 49

Jumping off the end of a file lseek allows you to set the current position to locations after the end of the file. For example, lseek(fd, 100, SEEK_END) moves the position 100 bytes past the end of a file. Now I) What happens if we read data after the end of a file? ii) What happens if we write data after the end of a file?

1 Answers

i) If you read after the end of the file, you'll read EOF just as if you were exactly at the end.

ii) If you write after the end of the file, zero bytes are inserted between the end and the place where you start writing. So the sequence

lseek(fd, 100, SEEK_END);
write(fd, buffer, size);

is roughly equivalent to

char zeros[100] = {0};
lseek(fd, 0, SEEK_END);
write(fd, zeroes, 100);
write(fd, buffer, size);

This is also what happens when you call truncate() or ftruncate() with a length greater than the current file size -- the file is extended with zero bytes.

Related