简体   繁体   English

Objective-C文件读取

[英]Objective-C File Read

I'm learning how to write simple Objective-C programs (without GUIs). 我正在学习如何编写简单的Objective-C程序(没有GUI)。 I made a new xcode project and have the following files on the top-level directory: 我创建了一个新的xcode项目,并在顶级目录中包含以下文件:

main.m
data.txt

How can I get the contents of data.txt as an NSString for use in main.m? 如何将data.txt的内容作为NSString获取,以便在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: 并传递@“data”作为参数,但它给了我错误:

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

What is the correct way to do this? 这样做的正确方法是什么?

Your code is actually totally correct. 你的代码实际上是完全正确的。 The problem is with your XCode project. 问题出在你的XCode项目上。 When you run your program, it gets run from the "Products" directory, the location of which depends on your XCode settings. 当您运行程序时,它将从“Products”目录运行,该目录的位置取决于您的XCode设置。 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: 如果您希望data.txt文件最终与可执行文件位于同一位置,那么可以在运行时找到它,您需要将文件添加到“复制文件”构建阶段,目标设置为“产品” “文件夹:

如何在XCode 7中复制文件

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. 您需要将路径作为参数传递给程序,然后使用[[NSProcessInfo processInfo] arguments]来获取路径。 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. 你需要以某种方式指定一个完整的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM