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?
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".
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:
SEEK_END supportThat 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With