appending data to a file without loading the file into memory?

Discussion in 'iOS Programming' started by djcraze, Apr 18, 2009.

  1. djcraze macrumors regular


    Jul 3, 2007
    So, I want to save data to an already made file; but I can't sem to find out how. I know how to write to a file, and read a file but not append a file. I tried fopen("","a+"), but the iPhone app crashes when I use fprintf.. :(.

    Any suggestions would be great!

    k, thx, bie
  2. djcraze thread starter macrumors regular


    Jul 3, 2007
    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
    [myHandle seekToEndOfFile];
    [myHandle writeData:data];
    [myHandle closeFile];
    for anyone who cares.
  3. cwe7976 macrumors newbie

    Jun 6, 2009
    Hey, I am using this method and have it working on the simulator fine.

    When i boot it up on the actual iPhone though, it doesnt give an error or anything but does not actually update the file.. any ideas as to why?

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"txt"];
    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [myHandle seekToEndOfFile];
    //the minus 17 puts it back far enough to be in the correct place for adding new values in the plist
    unsigned long long loc = [myHandle offsetInFile] - 17;
    [myHandle seekToFileOffset:loc];
    NSString *theKey = [NSString stringWithString:@"1"];
    NSString *theValue = [NSString stringWithString:@"one"];
    NSMutableString *newKeyValuePair = [NSMutableString stringWithString:@"\t<key>"];
    [newKeyValuePair appendString:theKey];
    [newKeyValuePair appendString:@"<\key>\n\t<string>"];
    [newKeyValuePair appendString:theValue];
    [newKeyValuePair appendString:@"</string>\n</dict>\n</plist>\n];
    NSData *theData = [newKeyValuePair dataUsingEncoding:NSUTF8StringEncoding];
    [myHandle writeData:theData];
    [myHandle closeFile];
    the best part is I include:
    [plistDict setObject:theValue forKey:theKey];
    which does infact add the value to the dictionary for that run, but upon next run it is gone...

    In the simulator though, it adds the value to the dictionary at runtime AND it is still there upon reboot.

  4. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
    Is the file in a writable directory?

    Documents directory is writable. Bundle directory on the iPhone is not.
    If you want to append to a file that's part of your app bundle, you will need to copy it to a writable directory first.

Share This Page