我试图使用ifstream打开一个文件,但无论我尝试过什么解决方案,似乎都不起作用;我的程序总是输出"unable to open“。下面是我的完整代码。任何帮助都是非常感谢的!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
string junk;
ifstream fin;
fin.open("somefile.txt");
if(fin.is_open())
{
fin >> junk;
cout << junk;
}
else
{
cout << "unable to open" << endl;
}
fin.close();
return 0;
}此外,与创建的可执行文件位于同一目录中的somefile.txt的内容如下:
SOME
FILE发布于 2013-02-21 07:26:22
正如一些评论者所建议的那样,很可能这个文件真的不存在,因为你在错误的地方寻找它。尝试使用文件的绝对路径,而不是仅仅假设它是您期望的位置。
并使用strerror(errno)输出更有用的错误消息。
// ...
fin.open("C:\\path\\to\\somefile.txt");
// ...
else
{
cout << "unable to open: " << strerror(errno) << endl;
}https://stackoverflow.com/questions/14991123
复制相似问题