简体   繁体   中英

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)?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM