在 C++ 中有没有办法转到文本文件中的特定行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5207550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C++ is there a way to go to a specific line in a text file?
提问by Jim
If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?
如果我使用 fstream 打开一个文本文件,是否有一种简单的方法可以跳转到特定的行,例如第 8 行?
回答by Xeo
Loop your way there.
在那里循环。
#include <fstream>
#include <limits>
std::fstream& GotoLine(std::fstream& file, unsigned int num){
file.seekg(std::ios::beg);
for(int i=0; i < num - 1; ++i){
file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
return file;
}
Sets the seek pointer of file
to the beginning of line num
.
将 的查找指针设置file
为行的开头num
。
Testing a file with the following content:
测试包含以下内容的文件:
1
2
3
4
5
6
7
8
9
10
Testprogram:
测试程序:
int main(){
using namespace std;
fstream file("bla.txt");
GotoLine(file, 8);
string line8;
file >> line8;
cout << line8;
cin.get();
return 0;
}
Output: 8
输出: 8
回答by Morten Kristensen
回答by Teodor Ciuraru
Here is a working and neat example with std::getline()
if the lines have the same length:
这是一个有效且简洁的示例,std::getline()
其中线条是否具有相同的长度:
#include <iostream>
#include <fstream>
#include <string>
const int LINE = 4;
int main() {
std::ifstream f("FILE.txt");
std::string s;
for (int i = 1; i <= LINE; i++)
std::getline(f, s);
std::cout << s;
return 0;
}
回答by dmckee --- ex-moderator kitten
In general, no, you have to walk down using a strategy similar to what Xeo shows.
一般来说,不,您必须使用类似于Xeo 所示的策略走下来。
If as netrom saysyou know the lines have fixed length, yes.
如果正如netrom 所说,您知道行具有固定长度,则是。
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.
即使事先不知道行的长度,但是 (1) 你会想要跳很多次并且 (2) 你可以保证在你可以制作文件的同时没有人弄乱你的文件通过以形成索引,然后使用它。