Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios not finding a txt file using stringWithContentsOfFile

I have a text file thetext.txt. Which is in my project and is copied on build, in build settings. In the same way that my GL shaders and textures are (which work fine.)

NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:@"thetext.txt"
                                       encoding:NSUTF8StringEncoding
                                          error:&errorReading]
             componentsSeparatedByString:@"\n"];

NSLog(@"Reading error  %@",errorReading); 

It prints the following to console.

Reading error  Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x896fff0 {NSFilePath=thetext.txt, NSUnderlyingError=0x896ff60 "The operation couldn’t be completed. No such file or directory"}

Have I missing something?

like image 547
Andrew Avatar asked Dec 02 '22 22:12

Andrew


1 Answers

This fails because you are passing the file name and not the path to the file. Try something like this

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"thetext" ofType:@"txt"];
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:filePath
                                   encoding:NSUTF8StringEncoding
                                      error:&errorReading]
                componentsSeparatedByString:@"\n"];
NSLog(@"Reading error  %@",errorReading);

Hopefully there will be no error!

like image 51
Groot Avatar answered Mar 03 '23 09:03

Groot