如何 - 从文本文件中读取特定的组线

问题描述:

可能重复:
In C++ is there a way to go to a specific line in a text file?如何 - 从文本文件中读取特定的组线

请告诉我更聪明的方式来读取特定组线(行号以行号B)从C++的文本文件中使用标准C++库(不选择Boost)?

+0

比什么更聪明? – 2011-12-21 16:58:21

+0

而不是从开始读取文件以匹配那些行号来提取文本..! – Vignesh 2011-12-21 17:01:27

+0

我假设它在逐行处理时手动计数行,只消耗从A到B的行 – minus 2011-12-21 17:02:28

如果行长度不固定,并且没有索引,则不能比计算\n更好。

考虑这个例子的文件:

Hello\nThis is a multi\n-line\nfile, where is this?\n\nAgain? 

行1点开始于字节0,第2行第6,第3行,在22,在28 4行,第5行,在49和6号线,在50 - 有没有模式。

如果我们事先知道这些信息,例如在文件的开始,我们在某个表中获得了这些信息,我们可以为文件中的字节计算出我们所关心的行的字节偏移量,并使用搜索直接在那里跳转。

如果行宽度固定为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; 
} 

这是适用于小十岁上下的文件(它读取整个文件到一个std::string)。对于较大的文件,您可能需要做同样的事情,但使用mmap而不是使用映射区域作为迭代器。或者,您可以使用RandomAccess迭代器在文件中使用seek()。 (std::istream_iterator不这样做,它只是一个ForwardIterator所以不适合)。

+0

非常感谢。 – Vignesh 2011-12-21 17:37:16

+0

@Vignesh - 我用一个例子更新了它。一种从A行和B行之间阅读的通用方法。 – Flexo 2011-12-21 17:54:17

+0

我明白了,非常好,现在我必须尝试使用​​地图(适用于较大的文件)。再次,非常感谢。 – Vignesh 2011-12-21 21:40:56

好办法,我认为是计算的线和本安输出你想要的线,我认为更好的解决办法是标签,但嗯,这是我得到了它的工作,对不起我的noobieness:

在这例如我们要读取包含“狮子座3”的3号线,噢,不要忘了,包括图书馆或标题:iostreamstringfstream

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; 

而且如果u想使和if语句确保它有由于getline的工作方式,我认为这个词后面的空格:

if(lines == "Leo3 ") 
{ 
    cout << "Yay!"; 
}