some functions to write files are atomic and therefore quite convenient in the sense that they prevent file corruption should something happen at write-time.
-[NSData writeToFile:atomically:]
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
the problem is that they erase the file and replace it with the new content… And I need to just append one line to a huge file.
What is the best way to do that in an atomic way, not risking to corrupt that file should something happen?
PS: the file is too huge to read it in one string, update the string and then push the enormous string to the file system.
Thanks in advance.
The reason there is no function like that is because the atomic versions makes a copy of the file, writes everything to it and then renames the new file to the same name as the old one and finally removes the old file. As such the original file is actually never modified but rather replaced with a new file.
If you want atomic appends that are fast, you can use
fwriteandfsyncto get the acheived effect.fwrites that are for less than PIPE_BUF (4096 bytes on iOS) followed byfsyncare guaranteed to be atomic.Here is a short snippet for a category that will do the operation, note that it misses proper error-checking code for the syscalls.