Pages

September 19, 2013

Write and Append text to file

Sometimes you need to write to an already existing file, that is append text to file.
Here's an example.


/** Append text to a file located in the /Documents directory.

 If file does not exist it will be created from scratch.

 @param str String to write.
 @param fileName Name of the file.

 */
+ (void)writeAndAppendString:(NSString *)str toFile:(NSString *)fileName {

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if (0 < [paths count]) {
        NSString *documentsDirPath = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirPath stringByAppendingPathComponent:fileName];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            // Add the text at the end of the file.
            NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
            [fileHandler seekToEndOfFile];
            [fileHandler writeData:data];
            [fileHandler closeFile];
        } else {
            // Create the file and write text to it.
            [data writeToFile:filePath atomically:YES];
        }
    }
}



Download the ready-for-use source file (.m) of Write and Append text to file

No comments:

Post a Comment