C++ 如何从文本文件中读取特定行集
可能重复:C++ 如何从文本文件中读取特定行集,c++,file,file-io,C++,File,File Io,可能重复: P> >从C++中的文本文件使用标准C++库(不选择Boost)?< /P> > P>更准确的方法来读取特定的行(行A到B行)?如果行长度不固定,并且没有索引,则不能比“ \n S/更好”。 考虑以下示例文件: Hello\nThis is a multi\n-line\nfile, where is this?\n\nAgain? 第1行从字节0开始,第2行从字节6开始,第3行从字节22开始,第4行从字节28开始,第5行从字节49开始,第6行从字节50开始-没有模式 如果我
<> P> >从C++中的文本文件使用标准C++库(不选择Boost)?< /P> > P>更准确的方法来读取特定的行(行A到B行)?如果行长度不固定,并且没有索引,则不能比“<代码> \n S/
更好”。 考虑以下示例文件:
Hello\nThis is a multi\n-line\nfile, where is this?\n\nAgain?
第1行从字节0开始,第2行从字节6开始,第3行从字节22开始,第4行从字节28开始,第5行从字节49开始,第6行从字节50开始-没有模式
如果我们事先知道这些信息,例如,在文件的开头,我们在某个表中有这些信息,我们就可以为我们关心的行计算文件中的字节偏移量,并使用seek直接跳到那里
如果线宽固定为20字节:
Hello \nThis is a multi \n-line \nfile, where is this?\n \nAgain?
然后我们可以计算一行的开始作为一个简单的乘法-偏移到文件中
如果您正在寻找一种“通用”的方法,我建议您:
#include <sstream>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <string>
template <typename Iter, typename Count, typename T>
Iter find_nth(Iter it, const Iter end, Count c, const T match) {
while(c > 0 && it != end) {
if (match == *it++)
--c;
}
return it;
}
int main() {
std::ifstream in("test.txt");
std::ostringstream str;
str << in.rdbuf();
const std::string& s = str.str();
const int A=2, B=4;
const std::string::const_iterator begin=find_nth(s.begin(),s.end(), A, '\n');
const std::string::const_iterator end =find_nth(begin,s.end(), B-A, '\n');
const std::string range(begin,end);
std::cout << range << std::endl;
}
#包括
#包括
#包括
#包括
#包括
模板
Iter查找(Iter it,常数终端,计数c,常数匹配){
而(c>0&&it!=end){
如果(匹配==*it++)
--c;
}
归还它;
}
int main(){
std::ifstream-in(“test.txt”);
std::ostringstream str;
str我认为有一种方法是数一数行,然后输出你想要的行,我认为更好的解决方案是标签,但这就是我如何使它工作的,很抱歉我的不高兴:
在本例中,我们希望阅读包含“Leo 3”的行号3,哦,不要忘记包含库或标题:iostream
string
fstream
:
int count;
string lines;
ofstream FileC("file.txt",ios::app);
lines = "Leo \nLeo2 \nLeo3 \n";
FileC << lines;
FileC.close();
ifstream FileR("file.txt");
for(count = 1; count <= 3; count++)
getline(FileR, lines);
cout << lines << endl;
int计数;
弦线;
流文件C(“file.txt”,ios::app);
lines=“Leo\nLeo2\nLeo3\n”;
FileC,而不是从一开始就读取文件以匹配用于提取文本的行号。!我假设它是在逐行处理时手动计算行数,只消耗到的行数B@Vignesh当前位置没有比这更聪明的方法了。除非你没有告诉我们更多的信息,否则你所能做的就是猜A和B行从哪里开始如果这些行不是固定长度的,并且您没有某种索引,那么从一开始就读取整个文件并计数是最好不过的了\n
s@awoodland是的。这些行不是固定长度的。@Vignesh-我用一个从a行和B行之间读取的通用方法的例子更新了它。我得到了这个想法,非常好,现在我ave尝试地图(对于较大的文件)。再次感谢。
if(lines == "Leo3 ")
{
cout << "Yay!";
}