gpt4 book ai didi

c++ - 如何到 "select"当前目录?

转载 作者:行者123 更新时间:2023-11-28 07:39:30 25 4
gpt4 key购买 nike

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

最佳答案

为了在不使用完全限定路径的情况下打开 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()来更改应用程序的当前工作目录。

关于c++ - 如何到 "select"当前目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16123853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com