Reputation: 1465
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?
Upvotes: 4
Views: 609
Reputation: 19782
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:
Upvotes: 4
Reputation: 162722
Command line project, eh?
You'll want to pass the path to the file as an argument to the program and then use [[NSProcessInfo processInfo] arguments]
to grab the path. You can't just name a file and hope that the working directory at runtime has any correspondence to where the file actually is; you need to specify a full path somehow.
Upvotes: 3