Question

I want to read a list of integers from a text file, I just want to write code like

int temp;
fin>>temp;

But when I read the Cocoa documentation, I found NSFileHandle is suggested, and there is no method like I assumed, only one related method:

- (NSData *)readDataOfLength:(NSUInteger)length

Is there any class/method can help me do this in Objective C? Thanks.

Was it helpful?

Solution

I want to read a list of integers from a text file, I just want to write code like

int temp; fin>>temp;

You have a lot of choices for file access. If you want to use C++-style access, you can, but you naturally need to open the file using the appropriate C++ file or stream methods. If you use Objective-C++, though, you can easily mix C++ code into your Objective-C.

You can also use the C standard library file routines like fopen(), fread(), etc.

Using C or C++ to read files is often a good choice if the files are coming from a source other than your program, something beyond your control.

But when I read Cocoa document, I found NSFileHandle is suggested, and there is no method like I assumed, only one related method:

Again, lots of choices. Yes, you can use NSFileHandle to read bytes from the file into a NSData object, and then you can get ranges of bytes out of the data object. A much more common way to write and read data, though, is to use NSKeyedArchiver and NSKeyedUnarchiver:

NSData *data = [NSData dataWithContentsOfFile:pathToFile];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
int age = [unarchiver decodeIntForKey:@"Age"];
int weight = [unarchiver decodeIntForKey:@"Weight"];
NSString *name = [unarchiver decodeObjectForKey:@"Name"];

That's just the tip of the iceberg, though. It seems like a lot of code compared to what you were looking for, but it can also be a lot less work. Because objects and their relationships can be stored and read, you can read in a complex graph of objects with very little code:

OrgChart *chart = [NSUnarchiver unarchiveObjectWithFile:pathToFile];

Another option is to use property lists, which are very easy to use, but limited in the data types that can be used.

If you want to learn more about these topics, read Archives and Serializations Programming Guide, Property List Programming Guide, and File System Programming Guide.

OTHER TIPS

You could use Objective-C++ and iostreams as you're used to.

You could use the C I/O functions like fopen and fscanf. (Probably what I'd do.)

Apple provides NSScanner for parsing, but it only reads from a string, not from an input stream. If you really want to use it, first you'll have to read your whole file (or a large chunk) into an NSString (or an NSData and then convert that to NSString).

If you can require the text file to be in JSON format, you can read it in one gulp and use NSJSONSerialization to parse it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top