0
votes

I want to write binary to a file.

I am looking at the function std::ofstream::write().

It takes a pointer and how many bytes to write. Is there anyway I can do something simple like

ofstream.write(36);

instead of to do it in two lines like...

int out = 36; ofstream.write((char*)&out , 4);

2
No there is no such way. - πάντα ῥεῖ

2 Answers

2
votes

Since write uses a pointer, you need to provide an address. An easy way of doing it on a single line is to write a helper function, like this:

inline void write(ostream& o, int n) {
    o.write(&n, sizeof(int));
}

Now you can do it on one line:

int foo() {
    ofstream ofs("aaa");
    write(ofs, 36);
    write(ofs, 42);
}
1
votes

No, there is no way.​​​​​​​​​​​​​​​