Which is faster? ifstream
or fread
.
Which should I use to read binary files?
fread()
puts the whole file into the memory.
So after fread
, accessing the buffer it creates is fast.
Does ifstream::open()
puts the whole file into the memory?
or does it access the hard disk every time we run ifstream::read()
?
So... does ifstream::open()
== fread()
?
or (ifstream::open(); ifstream::read(file_length);
) == fread()
?
Or shall I use ifstream::rdbuf()->read()
?
edit: My readFile() method now looks something like this:
void readFile()
{
std::ifstream fin;
fin.open("largefile.dat", ifstream::binary | ifstream::in);
// in each of these small read methods, there are at least 1 fin.read()
// call inside.
readHeaderInfo(fin);
readPreference(fin);
readMainContent(fin);
readVolumeData(fin);
readTextureData(fin);
fin.close();
}
Will the multiple fin.read() calls in the small methods slow down the program? Shall I only use 1 fin.read() in the main method and pass the buffer into the small methods? I guess I am going to write a small program to test.
Thanks!
Are you really sure about fread
putting the whole file into memory? File access can be buffered, but I doubt that you really get the whole file put into memory. I think ifstream::read
just uses fread
under the hood in a more C++ conformant way (and is therefore the standard way of reading binary information from a file in C++). I doubt that there is a significant performance difference.
To use fread
, the file has to be open. It doesn't take just a file and put it into memory at once. so ifstream::open == fopen
and ifstream::read == fread
.