我正在学习C++文件I / O,并且无法打开文件进行读取。我在Eclipse CDT(Ubuntu 18.04)和Visual Studios(Windows 10)中都尝试了一个简单的隔离文件输入程序。在Visual Studios中,它可以毫无问题地读取文件,但是在Eclipse中,当我打开文件时会设置failbit标志。我试图.clear()failbit标志,以查看它是否仍然能够读取文件,但它正在读取文件,就好像它是空的一样。
我的程序如下:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream f;
f.open("test.txt");
if (!f.is_open()) {
cout << "file could not be opened" << endl;
cout << "failbit? " << (f.fail() ? "yes" : "no") << endl;
return -1;
}
cout << "file opened successfully" << endl;
string line;
int i = 0;
while (f.peek() != EOF) {
getline(f, line);
cout << "line " << i << ": " << line << endl;
i++;
}
}
这在VS上工作,但我也需要在Eclipse上工作。欢迎任何建议,谢谢。
最佳答案
Eclipse的大多数版本都从项目所在的文件夹中执行该程序,如果您在项目目录中有该文件,请尝试将其移动/复制到可执行文件所在的调试目录中。
关于c++ - ifstream.open()在Eclipse CDT中设置failbit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61162116/