代码在 g++ 中运行完美,但在 Xcode 中不完美 - 找不到文件 [英] Code runs perfect in g++ but not in Xcode - Cannot find File

查看:23
本文介绍了代码在 g++ 中运行完美,但在 Xcode 中不完美 - 找不到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含内容的文本文件.它与 cpp 文件位于同一文件夹中.我已经多次确认该文件存在.当我运行 g++ 时,编译并运行它会找到该文件.当我在 Xcode 中运行它时,它不起作用.如果找不到文件.

I have created a text file with content. It is located in the same folder as the cpp files. And I have confirmed several times that the file exists. When I run g++, compile and run it finds the file. When I run it in Xcode, it does not work. 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;
}

推荐答案

您的文件无法打开,因为 XCode 在默认的 build 位置从 IDE 启动,这实际上是一个临时目录你的磁盘.如果您想在启动时将工作目录更改为其他目录(例如可以找到文件的位置):

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. If you want change the working directory at launch-time to something else (like the location where your files can be found):

  1. 选择产品/编辑方案...菜单选项.
  2. 在左侧列表中选择运行架构.
  3. 右窗格底部的选项标签应该是工作目录"选项.选中复选框并将自定义工作目录设置为您知道的某个位置(您的/Users/yourname"主目录是我使用的一个不错的位置).
  4. 确保从 IDE 执行程序所需的所有当前目录"数据文件都在此目录中.
  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).
  4. Make sure any "current directory" data files you need for your program execution from the IDE are in this directory.

如果您没有看到它,这也是您可以配置同一对话框的命令行参数(在另一个选项卡上)的地方.

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.

这篇关于代码在 g++ 中运行完美,但在 Xcode 中不完美 - 找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆