0

What is a fast and simple way to read a string line-by-line?

I am currently using Xcode, although solutions in any language are welcome.

For reference, I would prefer to make a function that allows me to read it much like one could read lines from a file in C#:

lineString = handle.ReadLine();
dhirschl
  • 2,088
  • 13
  • 18
Timo
  • 7,992
  • 4
  • 49
  • 67
  • Xcode is not a language - it's just an IDE - it supports programming in numerous languages, such as Objective C, Objective C++, C, C++, asm, etc. – Paul R Mar 21 '11 at 14:32
  • @Paul R: Good point. However, I never implied that Xcode is a language. Nevertheless, I have changed the title according to your suggestion. ;-) – Timo Mar 21 '11 at 14:35
  • it was the line: "I am currently using Xcode, although solutions in any language are welcome." which prompted my comment. ;-) – Paul R Mar 21 '11 at 14:50
  • @Paul R: Hehe, I understood. Ok, for purism: _Technically_, it does not claim that Xcode is a language. I simply state that I welcome suggestions in any languge, even though I am using Xcode (which might lead people to believe that I am only looking for C/Objective-C code). But ok... let's focus on a solution :-) I appreciate your comments! – Timo Mar 21 '11 at 15:04

1 Answers1

2

The answer does not explain how to read a LARGE text file line by line. There is not nice solution in Objective-C for reading large text files without putting them into memory (which isn't always an option).

In these case I like to use the c methods:

FILE* file = fopen("path to my file", "r");

size_t length;
char *cLine = fgetln(file,&length);

while (length>0) {
    char str[length+1];
    strncpy(str, cLine, length);
    str[length] = '\0';

    NSString *line = [NSString stringWithFormat:@"%s",str];        
    % Do what you want here.

    cLine = fgetln(file,&length);
}

Note that fgetln will not keep your newline character. Also, We +1 the length of the str because we want to make space for the NULL termination.

DCurro
  • 1,797
  • 1
  • 15
  • 16