我正在寻找问题的答案,但在其他任何地方都找不到。
我正在尝试从.txt文件中读取文件,该文件与我的项目文件位于同一目录中。
我写了这个简单的代码:
ifstream file("file.txt");
std::string line;
std::getline(file, line);
cout << line;
...但是不幸的是,什么也没有发生,甚至没有错误或崩溃。
进一步研究之后,即使我将txt(“ file”)文件的名称更改为不存在的文件的名称,也不会发生任何事情。
我想念什么?
如果您的错误是由于打开文件引起的provide full path to the file
,请检查。
在您的代码中,您正在阅读第一行,因此,如果它是空白,那么您将看不到任何输出。
您必须遍历每行直到最后一行(到达文件EOF的末尾)。
// let's say your file is "test.txt" which is located in D\\MyDB
// ifstream file("file.txt");
ifstream file("D:\\MyDB\\test.txt"); // use full path instead and check manully whether the file is there or not
std::string line;
if(file.fail())
cout << "Opening file failed!" << endl;
else
while(std::getline(file, line))
{
cout << line;
}
如果在提供完整路径时可以使用,则您当前的路径与您的项目不同。
您可以使用一些API更改当前目录,因此,如果您在Windows上,请使用:SetCurrentDirectory(path);
,在Linux上,请使用:chdir(sDirectory.c_str());
**我的意思是编译器不是OS
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句