1

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 );
2
  • 4
    All you really need is ss << fin.rdbuf();. Commented May 14, 2014 at 0:19
  • but the problem is that I'm aiming for performance and all those >> operators for the ifstream class could really slow down my program And you know this because you've written your app and profiled accordingly, right? Commented May 14, 2014 at 0:51

2 Answers 2

2
  1. Get the size of the file, like you have done.
  2. Allocate an array of char to hold the contents.
  3. Read the entire file into the char array using istream::read.
  4. Create a istringstream that uses the char array. Use it to parse the data.
  5. Deallocate the array of char.

Update

Make sure you open the file in binary mode if you want to follow this strategy. Thanks @ooga.

Sign up to request clarification or add additional context in comments.

12 Comments

It might also be a good idea to open the file in binary mode.
How am I assigning the char array to the istringstream without making a copy of the content?
@grimgrom, Why do you need std::istringstream?
@ooga: "binary mode" only applies to Windows. Most programs don't need to be concerned with it.
@wallyk I'm well-aware of that (although it certainly does not "only apply to Windows"). But portability is important to most people.
|
0

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, i.e. wasting time and space.

You don't need to do this. Just ensure there is adequate buffering on the fstream.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.