Graphics Programs Reference
In-Depth Information
For the More Curious: Reading and Writing to the
Filesystem
In addition to archiving and NSData 's binary read and write methods, there are a few
more methods for transferring data to and from the filesystem. One of them, Core Data, is
coming up in Chapter 16 . A couple of others are worth mentioning here.
You have access to the standard file I/O functions from the C library. These functions look
like this:
FILE *inFile = fopen("textfile", "rt");
char *buffer = malloc(someSize);
fread(buffer, byteCount, 1, inFile);
FILE *outFile = fopen("binaryfile", "w");
fwrite(buffer, byteCount, 1, outFile);
However, you won't see these functions used much because there are more convenient
ways of reading and writing binary and text data. Using NSData works well for binary
data. For text data, NSString has two instance methods
writeToFile:atomically:encoding:error: and initWithContent-
sOfFile: . They are used as follows:
// A local variable to store an error object if one comes back
NSError *err;
NSString *someString = @"Text Data";
BOOL success = [someString writeToFile:@"/some/path/file"
atomically:YES
encoding:NSUTF8StringEncoding
error:&err];
if (!success) {
NSLog(@"Error writing file: %@", [err localizedDescription]);
}
NSString *x = [[NSString alloc] initWithContentsOfFile:@"/some/path/file"
encoding:NSUTF8StringEncoding
error:&err];
if (!x) {
NSLog(@"Error reading file: %@", [err localizedDescription]);
}
What's that NSError object? Some methods might fail for a variety of reasons. For ex-
ample, writing to the filesystem might fail because the path is invalid or the user doesn't
have permission to write to the specified path. An NSError object contains the reason for
a failure. You can send the message localizedDescription to an instance of NSEr-
Search WWH ::




Custom Search