在 C++有没有办法转到文本文件中的特定行?
如果我使用 fstream 打开文本文件,是否有一种简单的方法可以跳转到特定行,例如第 8 行?
If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
绕你的路去那里。
将
file
的查找指针设置为行num
的开头。测试包含以下内容的文件:
测试程序:
输出:
8
Loop your way there.
Sets the seek pointer of
file
to the beginning of linenum
.Testing a file with the following content:
Test program:
Output:
8
如果每行的长度相同,则可以使用 istream::seekg( ) 跳转到该位置并从那里读取。
If every line has the same length then you can use istream::seekg() to jump to the location and read from there.
如果行具有相同的长度,这是一个使用
std::getline()
的有效且简洁的示例:Here is a working and neat example with
std::getline()
if the lines have the same length:一般来说,不,您必须使用类似于Xeo 显示。
如果为 netrom 说你知道这些线有固定长度,是的。
即使事先不知道行的长度,但是(1)你会想要经常跳来跳去,并且(2)你可以保证在你可以制作一个文件的同时没有人会弄乱你的文件pass 形成索引,然后使用它。
In general, no, you have to walk down using a strategy similar to what Xeo shows.
If as netrom says you know the lines have fixed length, yes.
And even if the line lengths are not known in advance, but (1) you're going to want to jump around a lot and (2) you can guaranteed that no one is messing with your file in the mean time you could make one pass to form a index, and use that thereafter.
你也可以使用 while 循环
you can use while loop as well