1

I have a huge .txt file (like 100mb) and I don't want to load all the content into a NSString. So how can I read line by line this file?

I would like something like:

while ( endOfFile is not reached )
   line = readline();
Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • Alternative answers here: [Objective-C: Reading a file line by line](http://stackoverflow.com/questions/1044334/objective-c-reading-a-file-line-by-line). – Martin R Feb 28 '14 at 20:53

1 Answers1

1

It's also possible using C code (because ObjectiveC is a superset of C); there's the fgets function that reads exactly one line.

FILE *file = fopen([filename UTF8String], "r");
char buffer[256];
while (fgets(buffer, sizeof(char)*256, file) != NULL){
    NSString* line = [NSString stringWithUTF8String:buffer];
    NSLog(@"%@",line);
}

The only tricky part is the 256 you see in the code. You need to make sure that this number is greater than the number of characters in the longest line of your text file.

Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • Actually that is one of the answers to the question that I linked to: http://stackoverflow.com/a/20257340/1187415 . – Martin R Feb 28 '14 at 21:35
  • @MartinR I copied it from one of my projects, but it's possible that I copied the snipped form another source (your link maybe) a while ago. – Merlevede Feb 28 '14 at 21:46