views:

693

answers:

3

Hi,

I want to log my log strings to a file.

I implemented the following method:

void QuietLog (NSString *format, ...) {
    if (format == nil) {
        printf("nil\n");
        return;
    }
    va_list argList;
    va_start(argList, format);

    NSMutableString *s = [[NSMutableString alloc] initWithFormat:format
                                                       arguments:argList];
    [s replaceOccurrencesOfString: @"%%"
                       withString: @"%%%%"
                          options: 0
                            range: NSMakeRange(0, [s length])];

    #ifdef LOGTOFILE_MODE
    NSData *dataToWrite = [s dataUsingEncoding: NSUTF8StringEncoding];
    [dataToWrite writeToFile: Log_FilePath atomically: YES];
    #else
    printf("%s\n", [s UTF8String]);
    #endif

    [s release];
    va_end(argList);
}

The writeToFile method replaces all the data that was in a file before with the last string. But I'd like to keep the previously added data and add to it a new string.

What is the problem with writeToFile? Why does it overwrites all existing data? How can I add new strings instead of overwriting the old ones?

Thanks.

+1  A: 

How about this simple code (ref apple support forum):

@implementation NSData (NSDataExtensions)

- (BOOL) appendToFile: (NSString *) path atomically: (BOOL) flag
  {
    NSFileHandle fh = [NSFileHandle fileHandleForWritingAtPath: path];

    if(fh)
      @try
      {
         [fh seekToEndOfFile];
         [fh writeData: self];   
         [fh closeFile];   
         return YES;
      }
      @catch(id error) {}

    return NO;
  }
@end
Michael Pryor
I think it's fine, but won't it work very slow? Especially when I have a big file?The iPhone will have first to read the whole data, then append new data and only then to write the whole data again.
Ilya
+2  A: 

How about using NSFileHandle, thus:

NSData *dataToWrite = [s dataUsingEncoding: NSUTF8StringEncoding];
NSFileHandle* outputFile = [NSFileHandle fileHandleForWritingAtPath:Log_FilePath];
[outputFile seekToEndOfFile];
[outputFile writeData:dataToWrite];
zpasternack
+1  A: 

Here's another approach that I wrote about a few months ago which describes how you can direct NSLog to write output to a file. You can either truncate the output on each execution or append the output to a log file.

http://iPhoneDeveloperTips.com/general/write-debug-output-to-a-file.html

Hope that helps.

John