Home > OS >  Rewind a stream, both ifstream as well as strstream
Rewind a stream, both ifstream as well as strstream

Time:03-07

I want to write a HEX file reader. It should support two different formats: Intel HEX and a "ROM" file format where each line contains a pair of address and 16 bit hex value. The reader shall identify the format. For that purpose it must read at least some lines to check if it's at least one valid format.

The file stream shall be passed to the reader with a function like:

class CHexFile { 
public:
    bool Open(std::istream& stream);
    uint16_t GetChunk(); // Return two bytes of the stream.
private:
    void Validate(std::istream& stream);
};

The parameter type is std::istream because this allows to prepare a std::strstream in a unit tester and pass the stream to the function.

It's possible to detect the stream format and validate the entire stream. But how can I rewind the stream after validation (or format detection) and actually retrieve the data?

Note: I have to use a rather old C compiler from 2006 (Paradigm). Therefore I can't use fancy features from C 1x or C 2x.

CodePudding user response:

Call stream.clear(); stream.seekg(0, std::ios_base::beg);. That should rewind any stream that can be rewound. Of course some istreams cannot be rewound, such as std::cin, so you'll want to check for an error after seekg().

  • Related