C++读取txt文件?
您好,我使用 ubuntu (Linux),使用 g++ 编译器。
我有一个非常奇怪的情况,昨天我的代码工作正常,我没有做任何事情,但今天,它不起作用。这是我的代码:
ifstream file;
file.open("users.txt", ios::in);
if(file.is_open()){
int counter = 0;
string readLine;
file.seekg(0, ios::end);
if (file.tellg() == 0)
file.close();
else {
while(!file.eof()){
getline(file,readLine);
cout << "whats happening?" << readLine << endl;
// I was suppose to do process here, but i comment it for debug purposes
}
openFile.close();
}
我不明白为什么,我花了2个小时调试,昨天,它可以读取用户数据,但今天,我打开相同的项目,但它无法读取文件。我 100% 确定,路径是正确的并且文件有内容。但我的结果是:
Whats happening?
仅此而已,没有别的。救救我吧,我看这个东西快疯了!!!!!!!
Hi Iam using ubuntu (Linux), using g++ compiler.
I have a very weird situation, yesterday my code was working fine, I didn't do anything, but today, its not working. Here is my code:
ifstream file;
file.open("users.txt", ios::in);
if(file.is_open()){
int counter = 0;
string readLine;
file.seekg(0, ios::end);
if (file.tellg() == 0)
file.close();
else {
while(!file.eof()){
getline(file,readLine);
cout << "whats happening?" << readLine << endl;
// I was suppose to do process here, but i comment it for debug purposes
}
openFile.close();
}
I dont understand why, I spent 2 hours debugging, yesterday, it can read users data, but today, i open the same projects, but it cant read the file. I am 100% sure, the path is correct and the file has contents. BUt my result is:
Whats happening?
Thats all, nothing else. Help me, I am going crazy look at this stuff!!!!!!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
file.seekg(0, ios::end);
将查找文件末尾。在开始阅读之前,您需要先回到开头。is.seekg(0, ios::beg);
file.seekg(0, ios::end);
will seek to the end of the file. You need to seek back to the beginning before you start reading ie.is.seekg(0, ios::beg);