首页 > 解决方案 > 在 C++ 中读取大文件,但也在 C++ 中读取小文件?

问题描述

我想制作一个 C++ 程序来读取大文件(例如每个 50Gb),而您只有 4 或 8Gb 的 RAM。我希望这个算法更快,并且也可以处理小文件。

这是我到目前为止的代码:

#include<iostream>
#include<fstream>
#include<string>

using namespace std;
//Making a buffer to store the chuncks of the file read:
// Buffer size 1 Megabyte (or any number you like)
size_t buffer_size = 1<<20;
char *buffer = new char[buffer_size];



int main(){
string filename="stats.txt";

//compute file size
size_t iFileSize = 0;
std::ifstream ifstr(filename.c_str(), std::ios::binary); // create the file stream    - this is scoped for destruction

if(!ifstr.good()){
    cout<<"File is not valid!"<<endl;
    exit(EXIT_FAILURE);
}
//get the file size
iFileSize = ifstr.tellg();
ifstr.seekg( 0, std::ios::end ); // open file at the end to get the size
iFileSize = (int) ifstr.tellg() - iFileSize;
cout<<"File size is: "<<iFileSize<<endl;
//close the file and reopen it for reading:
ifstr.close();
cout<<"Buffer size before check is:"<<buffer_size<<endl;
if(buffer_size>iFileSize){
        buffer_size=iFileSize;
}
cout<<"Buffer size after check is:"<<buffer_size<<endl;


ifstream myFile;

myFile.open(filename);

if(myFile.fail()){
        cerr<<"Error opening file!"<<endl;
        exit(EXIT_FAILURE);

}

if(!myFile.good()){
        cout<<"File is not valid!"<<endl;
        exit(EXIT_FAILURE);

}

if(!myFile.is_open()){
        cout<<"File is NOT opened anymore!"<<endl;
        return 1;
}

while(myFile.is_open()&&myFile){
    // Try to read next chunk of data
    myFile.read(buffer, buffer_size);
    // Get the number of bytes actually read
    size_t count = myFile.gcount();
     // If nothing has been read, break
    if (!count){
        break;
    }
    // Do whatever you need with first count bytes in the buffer:
    string line;
    while(getline(myFile, line)){
             if(!line.empty()){
                cout <<"Line: '" << line << "'" <<endl;
             }


    }

}
delete[] buffer;
buffer = NULL;
myFile.close();


return 0;

}

我的文件在文本行之间可能有空行,甚至第一行也可能是空行。因此,我在一个名为的小文件(大小为 128kb)上测试了该程序,以了解它是如何工作的。但它不起作用。即使文件很小,它也不会在屏幕上显示任何行。

怎么了?另外,如果我将缓冲区大小更改为非常小的数字,它只会读取前一两行,但为什么它不循环到文件末尾以读取和显示该小文件中的所有行?请问有什么帮助吗?

先感谢您!

这是测试文件:(它也以几个空行开头。)

Population UK: 97876876723


Population France: 898989













This is the test end of the file: Yay!

结果如下:并且没有显示文件中的行。 在此处输入图像描述

标签: c++c++11c++14

解决方案


推荐阅读