简体   繁体   English

代码可以在g ++中完美运行,但不能在Xcode中运行-找不到文件

[英]Code runs perfect in g++ but not in Xcode - Cannot find File

I have created a text file with content. 我创建了一个包含内容的文本文件。 It is located in the same folder as the cpp files. 它与cpp文件位于同一文件夹中。 And I have confirmed several times that the file exists. 而且我已经多次确认该文件存在。 When I run g++, compile and run it finds the file. 当我运行g ++时,编译并运行它会找到文件。 When I run it in Xcode, it does not work. 当我在Xcode中运行它时,它不起作用。 If fails to find the file. 如果找不到文件。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

Your file fails to open because XCode launches from the IDE in the default build location, which is actually a temporary directory off somewhere on your disk. 您的文件无法打开,因为XCode是从IDE的默认构建位置启动的,该位置实际上是磁盘上某个临时目录。 If you want change the working directory at launch-time to something else (like the location where your files can be found): 如果要在启动时将工作目录更改为其他目录(例如可以找到文件的位置):

  1. Select the Product/Edit Scheme... menu option. 选择产品/编辑方案...菜单选项。
  2. Select the Run schema in the left list. 在左侧列表中选择“ 运行”架构。
  3. At the bottom Options tab on the right pane should be a "Working Directory" option. 在右窗格底部的“ 选项”选项卡上,应有一个“工作目录”选项。 Check the checkbox and set the custom working directory to someplace you know (your "/Users/yourname" home directory is a decent place that I use). 选中复选框,然后将自定义工作目录设置为您知道的某个地方(您的“ / Users /您的名字”主目录是我使用的一个不错的地方)。
  4. Make sure any "current directory" data files you need for your program execution from the IDE are in this directory. 确保从IDE执行程序所需的任何“当前目录”数据文件都在此目录中。

And in case you didn't see it, this is also the place where you can configure command-line arguments (on another tab) of the same dialog. 如果您没有看到它,也可以在这里配置同一对话框的命令行参数(在另一个选项卡上)。

尝试使用XCode将文件添加到项目中,或改用绝对路径。

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

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