使用C ++在工作目录之外打开一个文件 [英] Opening a file in C++ outside of the working directory

查看:115
本文介绍了使用C ++在工作目录之外打开一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序会有几个资源文件,用户可以把它放在与可执行文件不在同一个文件夹的计算机上。如何打开这些文件?



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

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

是不成功的。我知道路径是正确的(复制和粘贴)。我找不到任何文件,但我认为它必须是可能的。 ( vim〜/ foo.txt )可以从以外的任何地方使用)。

解决方案假设你打算使用 ifstream 而不是 iostream ,你的代码是正确的。 ifstream 可以使用文件的路径以及工作目录中文件的名称。



否如果文件不存在,则会抛出异常,但会设置失败位。

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

if(!input)std :: cerr<< 无法打开文件! <<的std :: ENDL;

else
{
// ...
}

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


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.txt from anywhere other than ~ works, for example).

解决方案

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

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.

这篇关于使用C ++在工作目录之外打开一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆