問題描述
我創(chuàng)建了一個包含內(nèi)容的文本文件.它與 cpp 文件位于同一文件夾中.我已經(jīng)多次確認(rèn)該文件存在.當(dāng)我運(yùn)行 g++ 時,編譯并運(yùn)行它會找到該文件.當(dāng)我在 Xcode 中運(yùn)行它時,它不起作用.如果找不到文件.
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;
}
推薦答案
您的文件無法打開,因?yàn)?XCode 從 IDE 中的默認(rèn) build 位置啟動,該位置實(shí)際上是某個位置的臨時目錄你的磁盤.如果您想在啟動時將工作目錄更改為其他內(nèi)容(例如可以找到文件的位置):
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):
- 選擇產(chǎn)品/編輯方案...菜單選項(xiàng).
- 在左側(cè)列表中選擇運(yùn)行架構(gòu).
- 在右窗格的底部 選項(xiàng) 標(biāo)簽應(yīng)該是工作目錄"選項(xiàng).選中復(fù)選框并將自定義工作目錄設(shè)置為您知道的地方(您的/Users/yourname"主目錄是我使用的一個不錯的地方).
- 確保從 IDE 執(zhí)行程序所需的任何當(dāng)前目錄"數(shù)據(jù)文件都在此目錄中.
- 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.
如果您沒有看到,這也是您可以配置同一對話框的命令行參數(shù)(在另一個選項(xiàng)卡上)的地方.
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.
這篇關(guān)于代碼在 g++ 中運(yùn)行完美,但在 Xcode 中卻不是 - 找不到文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!