How do I change C file operation to Objective C?
char buf[32];
FILE *fp = fopen("test.txt", "r");
fscanf(fp, "%s", buf);
fclose(fp);
I want to change above C file operations to 开发者_JAVA技巧Objective-C.
How do I change?
Is not there fscanf kind of thing in Objective-C?
You don't. You can't scan from FILE *
directly into an NSString
. However, once you've read into the buffer, you can create an NSString
from it:
NSString *str = [NSString stringWithCString: buf encoding: NSASCIIStringEncoding]; // or whatever
NOTE, however, that using fscanf
as you have here will cause a buffer overflow. You must specify the size of the buffer, minus one for the trailing null character:
fscanf(fp, "%31s", buf);
Your best bet is to use NSData to read in your file, and then create a string from that.
NSData *dataContents = [NSData dataWithContentsOfFile: @"test.txt"];
NSString *stringContents = [[NSString alloc] initWithData: dataContents
encoding: NSUTF8StringEncoding];
Assuming your file is UTF8.
No sense messing around with buffers. Let the framework do the dirty work.
EDIT: Responding to your comment, if you really, truly need to read it line by line, check out Objective-C: Reading a file line by line
You just want to read a text file into a string?
NSError *error = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:@"test.txt" withEncoding:NSUTF8StringEncoding error:&error];
if(!fileContents) {
NSLog(@"Couldn't read file because of error: %@", [error localizedFailureReason]);
}
This assumes UTF8 encoding, of course.
精彩评论