Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ataylor2009

macrumors member
Original poster
Jan 27, 2009
78
0
I have searched Apple's developer website from hither to yon, and I cannot find anything that appears to answer this question. The NSFileHandle and NSFileManager APIs seem to deal only in entire files, not parts of files...

I need to read a bunch of data in from a text file. The data is in the form

int
string
string
int,int,int,int,int,int,int,int,int,int

How can I read the data into 13 different variables? I.e., my first variable is partID and I need it be the first 'int' shown above. Second variable is partName and I need it to be the first 'string' shown above, which is the second line of data. Etc.

In pseudocode I would say, "While not an end-of-line character, read data into the variable partID. When the end-of-line character is reached, break the loop and continue." Then lather, rinse and repeat until I've got all 13 variables set.

Also - the 10 int on the same line - how do I read those into separate variables? Am I going to be better off putting each int on its own line?

Thanks in advance.
 

cazlar

macrumors 6502
Oct 2, 2003
492
11
Sydney, Australia
Easiest (maybe not best?) way would be to read the whole thing in as a NSString (ie use stringWithContentsOfFile:encoding:error: ), then you could use componentsSeparatedByString: to split by \n (or whatever line endings you have in the file). This will give you an array of the 4 separate lines. Then throw into variables, and for the last one, split again using the comma to separate them. Potentially you could split by both /n and comma at once (to end up with a single array of the 13 items), but then if you have commas in your string lines it could stuff up, so might be better to do them separate.

Hope this helps. As I say, might not be best way but should work.
 

Eraserhead

macrumors G4
Nov 3, 2005
10,434
12,250
UK
read in each character and check for a "\n". Alternatively there is probably a method in NSString or something to read a line of a file directly.
 

autorelease

macrumors regular
Oct 13, 2008
144
0
Achewood, CA
Read the contents of the file as one string and split it with componentsSeparatedByString, then use an NSScanner to read the fields from each line.

The C standard library has functions to read a file line by line and parse input (see fgets(), fscanf(), sscanf(), etc.) but you'd have to remember to convert any C strings (char *) to NSStrings if you use them elsewhere in your Cocoa app. I wouldn't recommend using the standard library in Cocoa apps since there are better and safer alternatives, but it's essential when writing console-only apps in C or C++.

I'm not sure what kind of file you're reading in, but if this is something like a user's preference file, why not use a property list or NSUserDefaults?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.