C++ buffered file reading

2019-04-13 00:49发布

问题:

I wonder if reading a large text file line by line (e.g., std::getline or fgets) can be buffered with predefined read buffer size, or one must use special bytewise functions?

I mean reading very large files with I/O operations number optimization (e.g., reading 32 MB from the HDD at a time). Of course I can handcraft buffered reading, but I thought standard file streams had that possibility.

回答1:

Neither line-by-line, nor special byte-wise functions. Instead, the following should do your job:

std::ifstream file("input.txt");
std::istream_iterator<char> begin(file), end;

std::vector<char> buffer(begin, end); //reading the file is done here!
//use buffer. it contains the content of the file!

And you're done, as buffer contains the content of the file.