Sign in to follow this  
Samurai Jack

Custom IStream?

Recommended Posts

Greetings! I have a class, that is somekind of a virtual file. It can fake files from memory buffer, read real files from disk or rake files out of a zip archive. I was wondering woudn't it be great if I could have a child of istream class, which would be fully compatible with istream and could do all above described? For example: myfile >> yourAge; would read no matter from file, memory or zip and it would allways work. What I don't know is, istream (or perhaps even ifstream) has a lot of public members. What do I have to overide in order to work? Ok I know that it has to have its own Open/close, filsize and fileseek function but do I need something else too? Is there any known great example that displays it how simple is it done? I mean if I have to overide more than 15 functions I will not try it, because my basic class is very simple and it has no more than 5 or 6 public members. Thank you in advance!

Share this post


Link to post
Share on other sites
Yes you can and no you don't have to provide all of the member functions in std::istream, in particular you may notice none of std::istreams member functions are virtual. What you need to do is inherit std::istream_buf<T> and implement a couple (generally only 2 or 3) of its virtual functions then you can do

my_istream.rdbuf(new my_stream_buf());

There is a decent example here

Share this post


Link to post
Share on other sites
Quote:
Original post by Samurai JackI have a class, that is somekind of a virtual file. It can fake files from memory buffer, read real files from disk or rake files out of a zip archive.

Congratulations, you have reimplemented the basic design of IOStreams.

If you want to find a really, really excellent example of how to implement what you're trying to do, look no further than the code for the standard library that comes with your development system(s). In particular, the classes of the std::basic_streambuf<C, T> heirarchy.

What you might consider doing is to derive your implementation from std::basic_filebuf and reimplement the various virtual functions provided for that purpose. Then, simply create an object of std::basic_fstream and replace its redbuf() before performing an open() operation.

Faking files from a memory buffer is actually provided for you: good ol' std::stringstream. If you want good hints on how to implement it, see the implementation(s) that comes with your development system(s).

A good book on C++, such as Stroustrup, will tell you all about this.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this