2

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.

3 Answers 3

5

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 fwrite and fsync to get the acheived effect. fwrites that are for less than PIPE_BUF (4096 bytes on iOS) followed by fsync are 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.

@implementation NSData(AppendAtomically)

- (void)appendToFileAtomic:(NSString *)filePath
{
    NSAssert([self length] < PIPE_BUF, @"Cannot write messages longer than %d atomically", PIPE_BUF);

    const char *utfpath = [filePath UTF8String]; 

    FILE *f = fopen(utfpath, "ab");
    fwrite([self bytes], 1, [self length], f);
    fsync(fileno(f));
    fclose(f);
}

@end
4
  • The fsync thing sounds like what I need indeed, thanks! so there is no objective-c equivalent, it has to be older C-style functions as far as you know?
    – MikaelW
    May 17, 2012 at 15:51
  • @HampusNilsson Nice info! It would also be cool to add logic that will do the standard Cocoa writeAtomically method for cases when the file is greater than 4096. That ensure always atomic writes, but allow the speed benefit when small chunks need to be written.
    – jpswain
    Sep 15, 2012 at 23:36
  • What's the basis for claiming the write is atomic if you follow with sync and the size of the data is small? According to developer.apple.com/library/mac/documentation/Darwin/Reference/… this isn't the case. Am I reading the wrong docs?
    – Mike
    May 28, 2014 at 20:51
  • @Mike It's from the POSIX standard (although iOS has never been officially POSIX certified, so I guess it's not 100% certain): "Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set." fsync just makes certain the disk cache is flushed. Jun 2, 2014 at 12:07
0

There is one way is shown here and this stack overflow question is also showing similar.

Second way to do that is:

get the data from the file

 NSMutable *data = [NSData dataWithContentsOfFile:yourFilePath];
 [data appendData:yourNewData];
 [data writeToFile:yourFilePath];

The first one is more preferable as the file is hudge.

Hope this helps :)

1
  • Thanks! But is there a guarantee of atomicity with those first methods? That is, if the app is abruptly terminated during the NSFileHandle writedata call, is there a guarantee my file wont be modified/corrupted?
    – MikaelW
    May 17, 2012 at 15:48
0

Take a look at NSFileHandle. It will allow you to open a file for write, seek the cursor to the end of the file, and then append your data to the end of the file.

2
  • Thanks but what is really important to me is the atomicity guarantee. Like, if the app is abruptly terminated during the NSFileHandle writedata call, is there a guarantee my file wont be modified/corrupted?
    – MikaelW
    May 17, 2012 at 15:50
  • 1
    Unfortunately, I don't believe there is no such thing as appending to a file atomically. Because atomicity comes from writing to a copy and then moving the copy in place of the original. If you want atomicity, you'll have to make a copy of your file, append to it, then move it back.
    – mprivat
    May 17, 2012 at 16:20

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.