Ever asked yourself what happens if you write beyond the EOF? I ended up writing a small c program to find the answer that I needed.
TLDR:
If you write beyond the End Of File (EOF) The Linux kernel will write to the given offset/location without any error. Linux kernel will pad the file with zero under the hood. Although we can write beyond the EOF this doesn’t mean that we can also write before the beginning of the file. This is not possible and its undefined behavior.
File position starts at zero so it cannot be negative. The maximum value for the file position is bound to the size of C type that is used.
Anyway here is the C program that I wrote:
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define defer(x) do { ret = x; goto _defer; } while (0);
static char *file_path = "./test.txt";
static char *s = "hi mom!";
int main(void) {
int ret = 0;
FILE *f = NULL;
f = fopen(file_path, "w");
if (!f) {
fprintf(stderr, "ERROR: could not open file: %s: %s\n", file_path, strerror(errno));
defer(1);
}
// (offset: 10L, whence: SEEK_END) => EOF + 10
if (fseek(f, 10L, SEEK_END)) {
fprintf(stderr, "ERROR: could not seek to the end position: %s\n", strerror(errno));
defer(1);
}
fwrite(s, sizeof(char), strlen(s), f);
if(ferror(f)) {
fprintf(stderr, "ERROR: could not write to file: %s\n", strerror(errno));
defer(1);
}
_defer:
if (f) fclose(f);
return ret;
}
And here is the result:
$ gcc ./weof.c -o weof
$ ./weof
$ xxd ./test.txt
00000000: 0000 0000 0000 0000 0000 6869 206d 6f6d ..........hi mom
00000010: 21 !