November 2013
Beginner
325 pages
9h 47m
English
Reading a file into a string is very similar:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
@autoreleasepool {
NSError *error;
NSString *str = [[NSString alloc] initWithContentsOfFile:@"/etc/resolv.conf"
encoding:NSASCIIStringEncoding
error:&error];
if (!str) {
NSLog(@"read failed: %@", [error localizedDescription]);
} else {
NSLog(@"resolv.conf looks like this: %@", str);
}
}
return 0;
}
Here you are creating a new string by reading in the contents of a file as ASCII text. If the read fails (for example, if you did not have permission to read the file), then the method returns nil. In that case, you print out the error’s localized description.
Read now
Unlock full access