Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these two ways of writing at the end of the file equivalent?

I want to add a 4 at the end of the file and I have thought that I can do this in 2 different ways:

First method:

int a = 4;
FILE *f = fopen("file.txt","wb");
fseek(f,0,SEEK_END);
fwrite(&a,sizeof(int),1,f);

Second method:

int a = 4;
FILE *f = fopen("file.txt","ab");
fwrite(&a,sizeof(int),1,f);

I think they are exactly the same. Am I right?

like image 900
sacacorchos Avatar asked Jan 30 '26 00:01

sacacorchos


2 Answers

These are not the same.

The "wb" mode will truncate the file to zero size, while the "ab" mode will open the file and simply place the file pointer at the end.

So if you don't want to wipe out the contents of your file, use "ab".

like image 180
dbush Avatar answered Feb 01 '26 15:02

dbush


int a = 4;
FILE *f = fopen("file.txt","wb");
fseek(f,0,SEEK_END);
fwrite(&a,sizeof(int),1,f);

This doesn't work as you expect, because opening in "wb" truncates the existing file (empties it). If you changed the mode to "r+b" and seeked to the end, it would work similarly, assuming that SEEK_END is supported (the standard does not require it, but most implementations support it), but it would require that the file already exists (only w and a based modes will create a file when it does not exist).

Your second option is safer, because:

  1. It works even if the file doesn't already exist
  2. It doesn't rely on SEEK_END support
  3. It's (partially) multi-thread/multi-process safe (subject to varied implementation details)

That said, it's still not guaranteed; the C standard allows for some weird systems, where binary files might be larger than the data written due to the system imposing null padding at the end (e.g. files might be required to be a multiple of 512 bytes in size, so if you write 400 bytes, the file would end with 112 '\0's). I suspect these are the same sorts of systems that might not support SEEK_END. If you're on one of those systems, the appended data would be appended after the padding. That said, if you're on one of those systems, you've got other issues (you can't actually know where the "real" data ends without writing length metadata to the file itself; at that point, you're stuck prefixing all your files with a length and using a SEEK_SET based seek for when you want to append, and it gets nuts).

like image 36
ShadowRanger Avatar answered Feb 01 '26 15:02

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!