Reading a file with objective C

Discussion in 'Mac Programming' started by mikesown, Mar 28, 2007.

  1. macrumors member

    Aug 12, 2004
    Right now, I'm working on a translator of sorts. Basically it takes in words, and reads them against a database(a text file with commas seperating what is entered compared to the translation). Basically, I need to iterate line by line through a file. Unfortunately, I don't have a clue as to how to read a file in Objective C. I'm familiar with the FileReader class in Java. Is there anything like this in Objective C?

  2. macrumors 601


    Jan 6, 2004
    Western US
    A simplistic approach might use something like this:

    NSString *fileString = [NSString stringWithContentsOfFile:aFilePath]; // reads file into memory as an NSString
    NSArray *lines = [fileString componentsSeparatedByString:@"\n"]; // each line, adjust character for line endings
    That would probably work if you happen to know what line endings your source file uses. If the line ending type is unknown, it's more complicated (UNIX vs. Mac line endings, Unicode, UTF-8, etc.). You can also use that same technique to separate each line into words (again, if the separator is known). Also have a look at the NSScanner class for dealing with this, which may offer some more flexibility.

Share This Page