Question

I'm trying to to read lines one by one from an external txt file (about 180kb) using Objective-C. I have found this piece of code here on SO. The way I understand it this code will put every line in an element right?

- (IBAction)start:(id)sender; {
    NSString *fh = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
    for (NSArray *line in [fh componentsSeparatedByString:@"\n"]) {
        NSLog(@"output= %@",line[5]);
    }
}

I try to check if it is working by printing a line to my output but nothing happens, what am I doing wrong here?

Thanks,

Update: I made the suggested changes and as it turnout fh is indeed nil. If I make fh a string containing a piece of the text file (including a few \n) it works fine. I checked the file path but that seems allright, So the question now would be how come fh = nil?

NSString *fh = [NSString stringWithContentsOfFile:@"file:///Users/Mubanga/Documents/Blender/rough2.txt" encoding:NSUTF8StringEncoding error:nil];
if([fh length] == 0) {
    NSLog(@"fh=nil");
}
for (NSString *line in [fh componentsSeparatedByString:@"\n"]) {
    NSLog(@"output= %@",line);
    }

}
Was it helpful?

Solution

In addition to the required changes from @trojanfoe's answer, your fh is nil because the path is wrong. stringWithContentsOfFile: expects a simple path, not a file-URL. It should be:

 NSString *fh = [NSString stringWithContentsOfFile:@"/Users/Mubanga/Documents/Blender/rough2.txt" encoding:NSUTF8StringEncoding error:nil];

Generally, you should use the error parameter:

NSError *error;
NSString *fh = [NSString stringWithContentsOfFile:@"/Users/Mubanga/Documents/Blender/rough2.txt"
                                         encoding:NSUTF8StringEncoding
                                            error:&error];
if (fh == nil) {
    NSLog(@"Could not read file: %@", error);
} else {
    // ...
}

OTHER TIPS

The loop should be:

for (NSString *line in [fh componentsSeparatedByString:@"\n"]) {
    NSLog(@"output= %@",line);
}

(line will be an NSString and the output should be line, not line[5]).

I would do the character input by hand using native C calls. Just read() into a char[] buffer until you hit a newline, then process the buffer. No I won't write the code for you, check out the still-relevant K&R.

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