Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

djcraze

macrumors regular
Original poster
Jul 3, 2007
169
140
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
 
Code:
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];

for anyone who cares.
 
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?

Code:
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:
Code:
[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.
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.