user966939 user966939 - 2 months ago 21
C Question

Reserving space with fseek safe?

If you can guarantee that there is data to be written after seeking, is it safe to use

to reserve bytes at the beginning of a file? For example:

// reserve space
fseek(f, 4096, SEEK_SET);

// ...

// write some data after the reserved space
fwrite(buf, 1, bufsize, f);

// go back to the reserved space (to update it)

// ...

I noticed it works on Windows, but what about other platforms? Are there any gotchas to look out for?


Yes, this works fine. As long as you've opened the file in w or w+ mode, rather than a or a+, you can seek to any point in the file and write there, and it will write at that point in the file. Other parts of the file will be left unchanged; if they were never written, they'll contain zero bytes.

So if you do the following on a file that was just opened in w mode (which truncates the file first):

fseek(f, 10, SEEK_SET);
fwrite("abc", 1, 3, f);
fwrite("1234567890", 1, 10, f);

the contents of the file will be: