reading several lines

  • I need to read a file containing lines of text. Like this:
    abcd
    efg
    xyz

    After some searching of the docs I came up with:

    NSString *contents =
      [NSString stringWithContentsOfFile: file encoding:
    NSASCIIStringEncoding error: NULL];

    However, this does not seem to read beyond the first line, giving
    contents = "abcd" and nothing more.
    Repeated calling makes no difference, as could be expected. Changing
    the end of lines to Apple's and the encoding to the MacRoman encoding
    had no effect.

    How do I either repeatedly read the lines? Or all of them at once and
    scanning the resulting string? Because the text file can become
    fairly long, the first option could be desirable.

    The "String Programming Guide for Cocoa" did not help me further.
    Can someone point me in the right direction?

    Hans van der Meer
  • On 11. Oct 2007, at 22:24, Hans van der Meer wrote:

    > I need to read a file containing lines of text. Like this:
    > abcd
    > efg
    > xyz
    >
    > After some searching of the docs I came up with:
    >
    > NSString *contents =
    > [NSString stringWithContentsOfFile: file encoding:
    > NSASCIIStringEncoding error: NULL];

    try leaving the encoding part out. I have the following code in one
    of my projects:

    // set path to file
    NSString *data = [NSString stringWithContentsOfFile:path];

    that reads the entire file into an NSString. then I split it into
    lines with

    NSArray *array = [data componentsSeparatedByString:@"\n"];

    --
    GPG Key ID: 92AD877F7E4E32B9
    Fingerprint: 16B0 7DCD 3AB0 0C45 F5FD  581D 92AD 877F 7E4E 32B9
  • On Oct 11, 2007, at 2:38 PM, H M wrote:

    > try leaving the encoding part out. I have the following code in one
    > of my projects:
    >
    > // set path to file
    > NSString *data = [NSString stringWithContentsOfFile:path];
    >
    > that reads the entire file into an NSString. then I split it into
    > lines with
    >
    > NSArray *array = [data componentsSeparatedByString:@"\n"];

    Please don't leave the encoding out.  If you're going to use plain
    text files, you need to know what encoding you are using.  (If you
    need a suggestion, I recommend UTF-8.)

    If you know what line terminator your file uses,
    componentsSeparatedByString: is OK, although it may not be the most
    efficient solution for all purposes.  If you don't know what line
    terminator your file might be using, use methods like
    lineRangeForRange: or getLineStart:end:contentsEnd:forRange:.

    Douglas Davidson
previous month october 2007 next month
MTWTFSS
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Go to today