View Full Version : appending data to a file without loading the file into memory?
Apr 18, 2009, 09:34 PM
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
Apr 18, 2009, 10:22 PM
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
for anyone who cares.
Jun 6, 2009, 07:49 PM
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];
//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;
NSString *theKey = [NSString stringWithString:@"1"];
NSString *theValue = [NSString stringWithString:@"one"];
NSMutableString *newKeyValuePair = [NSMutableString stringWithString:@"\t<key>"];
NSData *theData = [newKeyValuePair dataUsingEncoding:NSUTF8StringEncoding];
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.
Jun 6, 2009, 08:41 PM
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.