[NSString initWithContentsOfFile encoding error]
Returns an
NSString
object initialized by reading data from the file at a given path using a given encoding.
- (id)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError**)error
Parameters of [NSString initWithContentsOfFile encoding error]
- path
- A path to a file.
- enc
- The encoding of the file at path.
- error
- If an error occurs, upon return contains an
NSError
object that describes the problem. If you are not interested in possible errors, pass inNULL
.
Return Value of [NSString initWithContentsOfFile encoding error]
An
NSString
object initialized by reading data from the file named by path using the encoding, enc. The returned object may be different from the original receiver. If the file can’t be opened or there is an encoding error, returnsnil
.
Example of [NSString initWithContentsOfFile encoding error]
NSStringEncoding enc;
NSString *result = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding: &enc
error:nil];
// Do something with the information about the encoding used
if ( enc == NSUTF8StringEncoding ) {
// ...
}
return result;
Example of [NSString initWithContentsOfFile encoding error]
NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"asc"];
path = [path stringByExpandingTildeInPath];
NSString *fileString = [NSString initWithContentsOfFile:path];
Example of [NSString initWithContentsOfFile encoding error]
// Fill myString with questions from the .txt file and then read .txt file
NSString *filePath = whatFile;
NSStringEncoding encoding;
NSError *error;
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&encoding error:&error];
if (!myString) {
myString = [[NSString alloc] encoding:NSUTF8StringEncoding error:&error]
}
if (!myString) {
myString = [[NSString alloc] encoding:NSISOLatin1StringEncoding error:&error]
}
if (!myString) {
NSLog(@"error: %@", error);
return;
}
// Load array
NSArray* myArray = [myString componentsSeparatedByString:@"\r"];
NSLog (@"\n \n Number of elements in myArray = %i", [myArray count]);