Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C File Read

I'm learning how to write simple Objective-C programs (without GUIs). I made a new xcode project and have the following files on the top-level directory:

main.m
data.txt

How can I get the contents of data.txt as an NSString for use in main.m?

I tried:

+ (NSString *)loadTextFileToString:(NSString*)fileDest {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileDest
                                                     ofType:@"txt"];
    NSError *error = nil;
    NSString *fileContent = [NSString stringWithContentsOfFile:filePath
                                                  encoding:NSUTF8StringEncoding
                                                     error:&error];
    if(error) {
        NSLog(@"ERROR while loading from file: %@", error);
    }
    return fileContent;
}

And passing @"data" as the argument but it gives me the error:

ERROR while loading from file: Error Domain=NSCocoaErrorDomain Code=258 "The file name is invalid."

What is the correct way to do this?

like image 276
kmell96 Avatar asked Mar 14 '23 16:03

kmell96


1 Answers

Your code is actually totally correct. The problem is with your XCode project. When you run your program, it gets run from the "Products" directory, the location of which depends on your XCode settings. If you want the data.txt file to end up in the same place as the executable, so it can be found at runtime, you need to add the file to the "Copy Files" build phase, with the destination set to the "Products" folder:

How to copy a file in XCode 7

like image 73
Mark Bessey Avatar answered Mar 23 '23 02:03

Mark Bessey