capikaw
capikaw

Reputation: 12946

How do you read a specific line number from a file in objective-c?

Hoping someone could point me in the right direction on finding how to read given line number(s) from a giant xml file (50k+ lines)?

Upvotes: 2

Views: 370

Answers (2)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

I did it this way:

I first loaded the file in memory (50k+ lines is big, but possible):

// Load file as single string.
// NSISOLatin1StringEncoding works most of the time.
// Use other encoding if necessary.
NSStringEncoding encoding = NSISOLatin1StringEncoding; 
NSError *error = nil;

NSString *fileAsString = [NSString stringWithContentsOfFile: path 
                                   encoding: encoding 
                                   error: &error];

if (error != nil)
    NSLog(@"%@", error);

Then I enumerated the lines using this:

__block NSUInteger currentLineNum = 1;

[fileAsString enumerateLinesUsingBlock:
    ^(NSString *line, BOOL *stop) 
    {

        // Handle line here...

        currentLineNum++;
    }];

This way you can easily find the line with the number you are looking for.

Perhaps there are better ways, but this works.

Upvotes: 0

Caleb
Caleb

Reputation: 124997

Since the lines in an XML file don't typically have a fixed length, there's no way to divine where the nth line in your file starts. You'll have to start reading from the beginning and count lines until you find the one that you want.

If you're going to access this file frequently, one thing you might want to do is to build an index for the file. Scan through the file and write the file offset of the beginning of each line into your index file. Since those offsets all have the same size, and since there's one for every line, you can find the offset of the nth line of your data file by reading the nth offset from the index file.

Upvotes: 1

Related Questions