PDA

View Full Version : appending data to a file without loading the file into memory?




djcraze
Apr 18, 2009, 08: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



djcraze
Apr 18, 2009, 09:22 PM
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];


for anyone who cares.

cwe7976
Jun 6, 2009, 06: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];
[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.

WTF.

firewood
Jun 6, 2009, 07: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.