Search code examples
c++ofstream

How to overload std::ofstream::put()?


I want to write int16_t values to file.

Therefore I tried to overload the std::ofstream::put() method.

#include <fstream>
#include <cstdint>

class Ofstream : public std::ofstream
{
public:
    Ofstream( const std::string & s) : std::ofstream(s) {}

    // for little-endian machines
    Ofstream & put(int16_t val)
    {
        char lsb, msb;
        lsb = (char)val;
        val >>= 8;
        msb = (char)val;
        put(lsb) && put(msb);
        return *this;
    }
    ~Ofstream() {}
};
int main()
{
    int16_t val = 0x1234;
    Ofstream ofile( "test");
    ofile.put(val);
}

At this I always get a Segmentation fault, so what's wrong with?


Solution

  • Your put() function calls itself rather than the base class version. So you get infinite recursion, which leads to stack overflow.

    Replace

    put(lsb) && put(msb);
    

    with

    std::ofstream::put(lsb) && std::ofstream::put(msb);