打开文件 c++ 时出现问题
必须是一个简单的答案,但我不知所措,这是返回错误的代码。我尝试过带或不带起始斜杠。
我不知道完整路径,我希望它是相对于exe的,这就是相对路径。我试图逃避斜线。
我的问题是当文件存在时我收到“打开文件时出错”。为什么它失败了?
ifstream myFile("/LOGS/ex090716.txt");
if (myFile.fail()) {cout << "Error opening file";}
else
{
cout << "File opened... \n";
//string line;
//while( getline(myFile, line) ) {
// cmatch results;
// regex rx("(p|q)(=)([^ %]*)");
// regex_search(line.c_str(), results, rx);
// string referringWords = results[3];
//}
myFile.close();
}
谢谢
Must be a simple answer but I am at a loss, here is the code that is returning an error. I have tried with and without the starting slash.
I won't know the full path, I want it to be relative from the exe, and that is the relative path. I tried escaping the slashes.
My problem is that i get "error opening file" when the file is there. why is it failing?
ifstream myFile("/LOGS/ex090716.txt");
if (myFile.fail()) {cout << "Error opening file";}
else
{
cout << "File opened... \n";
//string line;
//while( getline(myFile, line) ) {
// cmatch results;
// regex rx("(p|q)(=)([^ %]*)");
// regex_search(line.c_str(), results, rx);
// string referringWords = results[3];
//}
myFile.close();
}
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的问题到底是什么?如果您想测试文件是否打开,请使用
is_open()
。What is your problem exactly?! if you want to test if the file is open or not use
is_open()
.去掉前导斜线
Get rid of the leading slash
fail()
检查是否设置了failbit或badbit。
如果设置了failbit 或badbit,则该函数返回true。当输入操作期间发生除到达文件结尾之外的其他错误时,至少会设置这些标志之一。
或者
fail()
Check if either failbit or badbit is set.
The function returns true if either the failbit or the badbit is set. At least one of these flags is set when some error other than reaching the End-Of-File occurs during an input operation.
OR
相对路径:不要以
/
开头相对于程序目录而不是 cd:如果通过 PATH 找到程序,则不能仅使用 argv[0]。我不确定你能做什么是便携式的。您可能想要重复解析符号链接。
在 Linux 上,文件 /proc/self/exe 上的 readlink() 可以工作。
在 Windows 上,这应该有效:
通常,您应该使用 http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm
Relative path: don't start with
/
Relative to program dir rather than cd: you can't just use argv[0] if the program is found via PATH. I'm not sure what you can do that's portable. You may want to resolve symbolic links repeatedly.
On linux, readlink() on the file /proc/self/exe works.
On Windows, this is supposed to work:
In general, you should use http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm
perror() 可以相对容易地为您提供问题的详细描述,
但这不是 C++ 风格。
perror() can relative easy give you a detailed description of the problem
however this is not c++'ish.