How to write data(binary mode) in to a file only using std::filebuf?

854 Views Asked by At

Please examine following code :

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    char mybuffer[512];
    std::filebuf* optr = new std::filebuf();
    optr->pubsetbuf(mybuffer, 512);
    const char sentence[] = "Sample sentence";
    auto ptr = optr->open("bd.bin", std::ios::binary | std::ios::trunc | std::ios::out);
    if (ptr) {
        float fx = 13;
        auto n = optr->sputn(sentence, sizeof(sentence) - 1);
        n += optr->sputn(reinterpret_cast<const char*>(&fx), sizeof(fx));
        optr->pubsync();
    }
    optr->close();
    if(optr) { delete optr; }
    return 0;
}

After run this program no data has been written in to the file whilesputn -> n is returning valid amount of writtne characters(verified through debugging).

2

There are 2 best solutions below

2
einpoklum On

You code runs fine on my system, producing a bd.bin with 19 characters.

Are you sure this is exactly what you built and ran? Perhaps you're using a problematic compiler, or you're out of disk space or something.

2
Barry On

Use the right tool for the job. filebuf is just the buffer that is streamed into. The actual thing that does the writing in the iostreams API is std::ostream:

std::filebuf file;
if (file.open(...)) {
    std::ostream os(&file);
    os << sentence;
    os.write(reinterpret_cast<const char*>(&fx), sizeof(fx));
}

It's also easier to remember to use << and write() rather than deal with the maze of cryptically named functinos that is the streambuf API.