在工作目录之外用 C++ 打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10093891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:37:39  来源:igfitidea点击:

Opening a file in C++ outside of the working directory

c++file-io

提问by Ethan

I've got a program that is going to have several resource files that the user can put somewhere on the computer that isn't in the same folder as the executable. How do I get open those files?

我有一个程序,该程序将包含多个资源文件,用户可以将这些资源文件放在与可执行文件不在同一文件夹中的计算机上的某个位置。我如何打开这些文件?

I've found lots of answers saying that the reason things aren't working is that the file isn't in the working directory. I've tried providing fully qualified paths:

我发现很多答案都说事情不起作用的原因是文件不在工作目录中。我试过提供完全合格的路径:

ifstream str;
str.open("/home/millere/foo.txt")

but that was unsuccessful. I know the path was correct (copy and paste). I can't find any documentation on it, but I assume it has to be possible. (vim ~/foo.txtfrom anywhere other than ~works, for example).

但那是不成功的。我知道路径是正确的(复制和粘贴)。我找不到任何关于它的文档,但我认为它必须是可能的。(例如,vim ~/foo.txt来自~作品以外的任何地方)。

回答by Maxpm

Assuming you meant to use ifstreaminstead of iostream, your code is correct. ifstreamcan use a path to a file as well as the name of a file in the working directory.

假设您打算使用ifstream而不是iostream,那么您的代码是正确的。 ifstream可以使用文件路径以及工作目录中的文件名。

No exceptions are thrown if the file does not exist, but the fail bit is set. You should check for this before trying to do anything with the stream.

如果文件不存在,则不会抛出异常,但设置了失败位。在尝试对流执行任何操作之前,您应该检查这一点。

std::ifstream input("/home/bob/stuff.txt");

if (!input) std::cerr << "Could not open the file!" << std::endl;

else
{
    // ...
}

If you still cannot extract data from the file, the problem is somewhere else in your code.

如果您仍然无法从文件中提取数据,则问题出在您的代码中的其他地方。

回答by AKJ

I had the same issue and quickly noticed that, openwhen trying to get from a difference folder, had a different source directory (if using Cmake, the one that was specified by the cmake). You can find out, what the ouput/input source directory is by doing

我遇到了同样的问题,并很快注意到,open当尝试从不同的文件夹中获取时,有一个不同的源目录(如果使用 Cmake,则是由 cmake 指定的目录)。您可以通过执行了解输出/输入源目录是什么

system("ls")

or

或者

system("dir")

on windows to show the content of the current ouput/input directory.

在 Windows 上显示当前输出/输入目录的内容。