0

For example I have a list of some items in a text file. I want to read that data one by one. How can I do that in Swift? I've found NSString.stringWithContentsOfFile(path) but this reads whole file. In C++ i was using ifstream for that. Example:

ifstream fd(fileName);
    string code, type, title;
    int price, date;
    getline(fd, title);
    while (!fd.eof()) {         
        getline(fd, code, ',');
        fd >> ws;
        getline(fd, type, ',');
        fd >> ws;
        fd >> date;
        fd.ignore();
        fd >> price;
        fd.ignore();
    }
    fd.close();

And sample text file for that:

Title of List
K123, document, 1994, 12500
S156, photo, 2006, 7000
R421, book, 1998, 6000

How can I read files with Swift like that and get words in it one by one?

banderson
  • 65
  • 1
  • 11
  • 1
    This might be interesting: http://stackoverflow.com/questions/24581517/read-a-file-url-line-by-line-in-swift, even it it addresses your question only partially. – Also it *is* possible to call the BSD library functions `getline()` and `getdelim()` from Swift. – Martin R May 29 '15 at 19:57
  • `getdelim()` might be useful for that. I will try that. – banderson May 29 '15 at 20:16

1 Answers1

-1

Is it appropriate for you to read the whole file and then just parse the string into an array of characters/words? If so, consider using

func componentsSeparatedByString(_ separator: String) -> [AnyObject]

If you know there is a space or comma or whatever separator in between each token, this could be a possible solution. If that's not acceptable just comment below.

PDice30
  • 219
  • 1
  • 6
  • If I read the question correctly that's what the asker doesn't want to do. Instead they want to read the file a bit at a time. –  May 29 '15 at 19:48
  • Possible to use but it would be very inefficient for huge files. Also sometimes i may want to read first 'x' lines in the list so it won't be efficient for those cases. – banderson May 29 '15 at 19:54
  • Right, I was just giving OP a workaround, as I'm not sure what he or she is doing with this data. If they just to perform an operation on each token separated by a comma, it would be okay to parse the whole thing and then iterate through the array. Granted, it would likely be slower. EDIT: Just saw your comment. Yes this is definitely not a good solution then ha. – PDice30 May 29 '15 at 19:54
  • Take a look at the [NSData](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/) Class reference. That may be a jumping off point, sorry I don't have more information than that, good luck! – PDice30 May 29 '15 at 20:03