如何“选择”当前目录?

时间:2013-04-20 18:40:55

标签: c++ macos

我正在写一个比例计算器。在程序的开头,它从同一文件夹中的.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与我的代码位于同一个文件夹中。它是。

1 个答案:

答案 0 :(得分: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()来更改应用程序的当前工作目录。