itsaboutcode
itsaboutcode

Reputation: 25109

File Handling in Objective C

Is there anyway to do Files Handling in Objective-C? I am just trying to do simple read and write and can use 'c' but i am force to use Objective-C classes for that :@. I am looking into NSInputStream, but its going over my head. Is there any tutorial which explains how to use NSInputStream?

Upvotes: 1

Views: 6497

Answers (3)

TyN
TyN

Reputation: 41

I had trouble with basic file i/o when I first hit it in Obj-C as well. I ended up using NSFileHandle to get C style access to my file. Here's a basic example:

// note: myFilename is an NSString containing the full path to the file

// create the file
NSFileManager *fManager = [[NSFileManager alloc] init];
if ([fManager createFileAtPath:myFilename contents:nil attributes:nil] != YES) {
    NSLog(@"Failed to create file: %@", myFilename);
}
[fManager release]; fManager = nil;

// open the file for updating
NSFileHandle *myFile = [NSFileHandle fileHandleForUpdatingAtPath:myFilename];
if (myFile == nil) {
    NSLog(@"Failed to open file for updating: %@", myFilename);
}

// truncate the file so it is guaranteed to be empty
[myFile truncateFileAtOffset:0];

// note: rawData is an NSData object

// write data to a file
[myFile writeData:rawData];

// close the file handle
[myFile closeFile]; myFile = nil;

Upvotes: 3

jlehr
jlehr

Reputation: 15617

If all you need to do is really simple I/O, you can just tell an object to initialize itself from, or write itself to, a filesystem path or URL. This works with several Foundation classes, including NSString, NSData, NSArray, and NSDictionary among others.

Try starting out by looking at the following two NSString methods:

- initWithContentsOfFile:encoding:error:

- writeToFile:atomically:encoding:error:

Upvotes: 2

Related Questions