如何将ifstream返回到刚刚在C++中读取的行的开头

How do I return an ifstream back to the beginning of a line that was just read in C++?

本文关键字:读取 开头 C++ ifstream 返回      更新时间:2023-10-16

在我使用ifstream从文件中读取一行之后,有没有一种方法可以有条件地将流带回我刚刚读取的行的开头?

using namespace std;
//Some code here
ifstream ifs(filename);
string line;
while(ifs >> line)
{
//Some code here related to the line I just read
if(someCondition == true)
{
//Go back to the beginning of the line just read
}
//More code here
} 

因此,如果someCondition为true,那么在下一次while循环迭代中读取的下一行将与我刚才读取的行相同。否则,下一次while循环迭代将使用文件中的以下行。如果您需要进一步澄清,请毫不犹豫地询问。提前感谢!

更新#1

所以我尝试了以下方法:

while(ifs >> line)
{
//Some code here related to the line I just read
int place = ifs.tellg();
if(someCondition == true)
{
//Go back to the beginning of the line just read
ifs.seekg(place);
}
//More code here
}

但当条件成立时,它不会再次读取同一行。这里整数是可以接受的类型吗?

更新#2:解决方案

我的逻辑有错误。以下是我想要的正确版本,适用于任何好奇的人:

int place = 0;
while(ifs >> line)
{
//Some code here related to the line I just read
if(someCondition == true)
{
//Go back to the beginning of the line just read
ifs.seekg(place);
}
place = ifs.tellg();
//More code here
}

对tellg()的调用被移到了末尾,因为您需要查找到以前读取的行的开头。第一次我调用tellg(),然后在流更改之前调用seekg(),这就是为什么它看起来什么都没有更改(因为它真的没有更改)。感谢大家的贡献。

没有直接的方法可以说"回到最后一行的开头"。但是,您可以使用std::istream::tellg()回到您保留的位置。也就是说,在阅读一行之前,你会使用tellg(),然后使用seekg()回到这个位置。

然而,频繁调用查找函数是相当昂贵的,也就是说,我会考虑取消再次读取行的要求。

将fstream位置存储在文件中(查看文档)。

读取行。

如果出现这种情况,转到文件中的存储位置。

你需要这个:

  • http://en.cppreference.com/w/cpp/io/basic_istream/tellg

  • http://en.cppreference.com/w/cpp/io/basic_istream/seekg