問題描述
我創建了一個包含內容的文本文件.它與 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 從 IDE 中的默認 build 位置啟動,該位置實際上是某個位置的臨時目錄你的磁盤.如果您想在啟動時將工作目錄更改為其他內容(例如可以找到文件的位置):
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):
- 選擇產品/編輯方案...菜單選項.
- 在左側列表中選擇運行架構.
- 在右窗格的底部 選項 標簽應該是工作目錄"選項.選中復選框并將自定義工作目錄設置為您知道的地方(您的/Users/yourname"主目錄是我使用的一個不錯的地方).
- 確保從 IDE 執行程序所需的任何當前目錄"數據文件都在此目錄中.
- Select the Product/Edit Scheme... menu option.
- Select the Run schema in the left list.
- 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).
- 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 中卻不是 - 找不到文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!