如何解决在 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!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。