1

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).

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Buddhika Chaturanga
  • 957
  • 2
  • 14
  • 29

2 Answers2

0

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
0

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • ... but this is also not the write tool for OP's job, as s/he would probably want to be able to say `something << fx` and get the exact same effect as your `os.write()`, i.e. get the octets copied from memory into the file as is. – einpoklum Mar 06 '18 at 20:47
  • @einpoklum Well, if you could write that if you want to... `os << as_bytes(fx);` – Barry Mar 06 '18 at 21:15