开发者

Read string line-by-line (in Objective-C) [duplicate]

开发者 https://www.devze.com 2023-02-18 21:59 出处:网络
This question already has answers here: Objective-C: Reading a fi开发者_Python百科le line by line
This question already has answers here: Objective-C: Reading a fi开发者_Python百科le line by line (18 answers) Closed 2 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号