any reason not to use fopen()
--------- EDIT
I have found the easiest was to write lines to a text file is using
fopen() fputs() fclose()
Is there any reason to use some of the other code as indicated in the answers below?
------- END EDIT
I have found different code examples for writing to a text file. I looked at the apple dev web site and wasn't able to find a good answer there either. Seems as though you can use fopen() and fwrite() but I did't find good examples of that either. Below is what I am trying to use, and it does work. But I need to write multiple lines to the file. You will see at the end of开发者_StackOverflow this example below that I write the file 2 times, but there is only one line in the final output.
How do you write multiple lines?
Is this the correct code using "Apple iPhone" standards"?
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];
(void)[[NSFileManager defaultManager]
createDirectoryAtPath:parentDir
withIntermediateDirectories:YES
attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:@"myFile.txt"];
NSString *SendStr = [[NSString alloc] initWithFormat:@"This is a test\r\n"];
NSData *data0 = [ SendStr dataUsingEncoding:NSUTF8StringEncoding];
NSData* data = [[NSData alloc] initWithData:data0 ];
NSError *error = nil;
[data writeToFile:path options:NSDataWritingAtomic error:&error];
[data writeToFile:path options:NSDataWritingAtomic error:&error];
Thank you for the help!
NSString has methods to write its contents to file, so converting it to NSData is not necessary and you can do that with just one line:
[sendStr writeToFile:path atomically:YES encoding:NSUTF8Encoding error:&error];
If you want to write multiple lines to file at once you can accumulate them in 1 string object (possibly use NSMutableString for that) and write as one string. If you can't do that and want to append line to an existing line you'll have to use NSFileHandle class for that (as writing methods of NSString or NSData simple overwrite existing files):
NSData *data = [sendStr dataUsingEncoding:NSUTF8StringEncoding];
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:path];
[file seekToEndOfFile];
[file writeData: data];
P.S. couple of minor remarks
- In objective-c style variable names usually start with lower-case, and class names - with upper-case so I corrected
sendStr
name - it seems you don't need to create data variable - you could work just with data0
- if you create an object with alloc/init you must release it later to avoid memory leak - so your code should have
[sendStr release];
and[data release];
in the end
精彩评论