2013-04-20 37 views
0

我正在寫一個比例計算器。在程序開始時,它從相同文件夾中的.txt加載ASCII文本藝術圖片。如何「選擇」當前目錄?

這裏是我正在做它:

//Read picture 
string line; 
ifstream myfile("/Users/MYNAME/Desktop/MathScripts/Proportions/Value Finder/picture.txt"); 
if (myfile.is_open()) { 
    while (!myfile.eof()) { 
    getline(myfile, line); 
    cout << line << endl; 
    } 
    myfile.close(); 
} else cout << "Unable to load picture!!!" << endl; 
//Finish reading txt 

我聽說如果.TXT是在同一文件夾,你可以只使用名稱,而不是不得不說的目錄如何。含義而不是

/Users/MYNAME/Desktop/MathScripts/Proportions/Value Finder/picture.txt 

我只能使用「picture.txt」。這對我不起作用,我希望用戶能夠移動「Value Finder」文件夾而無需編輯任何代碼。

我在Mac和我正在使用CodeRunner;奇怪嗎?

請不要告訴我,以確保picture.txt是在同一文件夾作爲我的代碼。它是。

+0

你確定你有你的路徑上的當前目錄? – kronion 2013-04-20 18:42:47

+0

圖像正在加載。我只是想使用純picture.txt而不是/用戶/ MYNAME /桌面/ MathScripts /比例/值查找/ picture.txt – user2302825 2013-04-20 18:46:56

+3

picture.txt並不一定是您的代碼所在的文件夾中。如果您不想指定路徑,它需要位於運行代碼的文件夾中。 – Mat 2013-04-20 18:54:27

回答

1

爲了打開picture.txt不使用它必須駐留在當前工作目錄的完全限定路徑。當IDE啓動一個應用程序將其設置當前的工作目錄的應用程序駐留在同一個。如果picture.txt駐留在不同的目錄應用程序,你將不能夠只用它的名字將其打開。如果你需要得到當前的工作目錄,你可以這樣稱呼getcwd

char temp[MAXPATHLEN]; 
getcwd(temp, MAXPATHLEN); 

如果你想允許用戶指定目錄picture.txt是可以讓他們通過在命令行參數。然後,您可以使用提供的目錄和圖片文件名創建完全限定的路徑。現在

int main(int argc, const char **argv) 
{ 
    // Add some logic to see if the user passes a path as an argument 
    // and grab it. here we just assume it was passed on the command line. 
    const string user_path = arg[1]; 

    //Read picture 
    string line; 
    ifstream myfile(user_path + "/picture.txt"); 
    if (myfile.is_open()) 
    { 
     while (!myfile.eof()) { 
      getline(myfile, line); 
      cout << line << endl; 
     } 
     myfile.close(); 
    } 
    else 
    { 
     cout << "Unable to load picture!!!" << endl; 
    } 
    //Finish reading txt 

    return 0; 
} 

你可以做這樣的事情:

myapp "/user/USERNAME/Desktop/MathScripts/Proportions/Value Finder" 

,它會在那個目錄中的文件picture.txt。 (引號是必需的,因爲路徑名中有空格)。

注意:您可以撥打setcwd()更改應用程序的當前工作目錄。

+0

_getcwd和exe不匹配osx標記。 – 2013-04-20 20:50:33

+0

@ott Ack!感謝您指出了這一點。我已更新它以反映MacOS X上的使用情況 – 2013-04-20 20:55:45