So, I would like to parse a file through some kind of stream and I could indeed just simply use the ifstream class, but the problem is that I'm aiming for performance and all those >> operators for the ifstream class could really slow down my program. So I came up with the idea to somehow read the entire file into a std::stringstream, and then parse the file with the stringstream. I would like to do something like this, but I could not get it to work:
std::ifstream fin( p_Filename.c_str( ) );
fin.seekg( 0, std::ifstream::end );
int fileSize = static_cast<int>( fin.tellg( ) );
fin.seekg( 0, std::ifstream::beg );
std::stringstream ss;
ss.str( ).resize( fileSize );
fin.read( const_cast<char*>( ss.str( ).c_str( ) ), fileSize );
char
to hold the contents. char
array using istream::read
. istringstream
that uses the char
array. Use it to parse the data. char
. Update
Make sure you open the file in binary mode if you want to follow this strategy. Thanks @ooga.
Your conclusion is invalid.
If the >>
operators are going to be an overhead, they will have the same overhead operating on a string, and by reading the entire file before processing any of it you are just adding latency, ie wasting time and space.
You don't need to do this. Just ensure there is adequate buffering on the fstream.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.