Read string line-by-line (in Objective-C) [duplicate]
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();
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.
精彩评论