如何将ifstream返回到刚刚在C++中读取的行的开头
How do I return an ifstream back to the beginning of a line that was just read in C++?
在我使用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
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- ifstream 读取以 开头的每个文件
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- 从文件的开头读取,而不会浪费太多内存
- 是否可以在该用户注销后读取/打开用户密钥(HKEY_USERS中的密钥并以 s-1-5-21xxx 开头)
- 如何将ifstream返回到刚刚在C++中读取的行的开头
- 这是怎麽?在读取使用 Unicode 编码的文本文件后控制台输出的开头
- 在链表的开头插入时读取内存时出错
- C++fread读取文件开头的随机字符
- 从链表的末尾开始读取值,而不是从开头
- c++从文件开头读取到指定字节