
-----------------------------------
stkmtd
Mon Aug 24, 2009 4:57 pm

writing to a binary file
-----------------------------------
Ahoy, having some trouble writing binary to a file.

I'm just trying to write a simple program (as an exercise) that will output a file so that when I open it in a hex editor it will contain the value 0xDEADBEEF.

My code is as follows:

[code]
#include 
#include 
using namespace std;

int main (){
        ofstream deadbeefFile;
        char * myInt = {0xde, 0xad, 0xbe, 0xef};

        deadbeefFile.open ("deadbeef.bin", ios::out | ios::binary);

        deadbeefFile.write (myInt, 4);

        deadbeefFile.close();

        return 0;
}
[/code]

When I compile at the shell (with g++):

[code]
johnny@jnf-linux-desktop:~/coding/testProjects/binWrite$ g++ deadbeef.cpp
deadbeef.cpp: In function ?int main()?:
deadbeef.cpp:7: error: scalar object ?myInt? requires one element in initializer
[/code]

I'm new to C++, so any help is appreciated.

-----------------------------------
DemonWasp
Mon Aug 24, 2009 6:39 pm

RE:writing to a binary file
-----------------------------------
The compiler seems to be looking at your code and seeing "pointer to a char", not "an array of char". This alternate syntax compiles (though I haven't bothered testing it...):

[code]
        char myInt[] = {0xde, 0xad, 0xbe, 0xef};
[/code]

-----------------------------------
stkmtd
Mon Aug 24, 2009 7:30 pm

RE:writing to a binary file
-----------------------------------
Hoorah. It works. Thank you kindly.
