2011-10-20 93 views
1

我想在内存中读取的文件5MB左右大的txt文件... 文件具有这种格式(它是一个文本文件)阅读C++

ID 3: 0 itemId.1 0 itemId.2 0 itemId.5 1 itemId.7 ........................ 20 itemId.500 
ID 50: 0 itemId.31 0 itemId.2 0 itemId.4 2 itemId.70 ........................ 20 itemId.2120 
..... 

我怎么能做到这一点有效地在C + +?

+3

标准方式效率不高吗? –

+2

你应该真的重新考虑你认为“大”。估算是一项工程技能。 – pmr

+1

一般来说,根据平台的不同,5MB并不算大。大多数PC可以将5MB文件全部读入内存。 –

回答

5

逐行读取文件中的行:

ifstream fin ("file.txt"); 
string  myStr; 

while(getline(fin, myStr)) // Always put the read in the while condition. 
{       // Then you only enter the loop if there is data to 
    //use myStr data   // processes. Otherwise you need to read and then 
}       // test if the read was OK 
          // 
          // Note: The last line read will read up to (but not 
          //  past) then end of file. Thus When there is 
          //  no data left in the file its state is still 
          //  OK. It is not until you try and explicitly 
          //  read past the end of file that EOF flag is set. 

是有原因的不明确调用close看​​到:
https://codereview.stackexchange.com/questions/540/my-c-code-involving-an-fstream-failed-review/544#544

如果效率的主要目标(它可能不是)。然后将整个文件读入内存并从那里解析:请参阅下面的Thomas:Read large txt file in c++

+0

thx的教训(并不downvoting我):p +1 –

+0

如果你想在行中使用分隔符,你还会推荐这种方法吗? –

+0

@碎片:你可以使用'getline(fin,myStr,'#')'作为散列分隔符等等,但否则代码是一样的。 –

3

使用file stream

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 
    string line; 
    ifstream myfile ("example.txt"); 
    if (myfile.is_open()) 
    { 
     while (getline(myfile, line)) 
      cout << line << endl; 

     myfile.close(); 
    } 
    else 
    { 
     cout << "Unable to open file"; 
    } 

    return 0; 
} 

5MB确实不是一个大文件。该流将照顾您一次阅读块,但真的;几乎所有运行的机器都可能读取5MB到内存中没有问题。

+0

这有冗余代码,并会尝试读取太多的代码行。在这种情况下,使用已建立的成语来代替文本('while(getline(myfile,line))')。 –

+0

@Konrad:是的,我很懒,只是把它复制出来。我想我应该修好它......谢谢。 –

4

将整个文件读入内存,然后处理内存中的内容。

当电机保持旋转时,文件资源(例如硬盘驱动器)效率最高。因此,一次较大的数据读取比5次读取少量数据的效率更高。

在大多数平台上,内存访问速度比文件快。使用这些信息,可以通过将数据读入内存然后处理内存来提高程序的效率。

将这两种技术结合起来会产生更好的性能:在一次事务中将尽可能多的数据读入内存,然后处理内存。

有些人声明大数组charunsigned char(用于二进制数据)。其他人告诉std :: string或std :: vector保留大量内存,然后将数据读入数据结构。

此外,块读取(a.ka. istream::read())将绕过C++流设施的大部分缓慢部分。

+0

好资料,thx ^^ –