Reputation: 85
I am trying to convert C style file IO into C++ style file IO. I need to write the number 42 as a 4-byte signed integer.
Here's an example of what C type IO that I tried that worked
#include <stdio.h>
#include <string>
#include <fstream>
using namespace std;
int main()
{
FILE *myFile;
myFile = fopen ("input_file.dat", "wb");
int magicn = 42;
fwrite (&magicn, sizeof(magicn), 1, myFile);
fclose (myFile);
return 0;
}
I am trying to convert the above code to C++ type IO based on a suggestion from a different question I asked (How to write a string with padding to binary file using fwrite?).
Here's my attempt:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ofstream myFile ("input_file.dat", ios::binary);
int magicn = 42;
myFile << setw(sizeof(magicn)) << magicn;
myFile.close();
return 0;
}
However, the output I am expecting when I use the 'xxd -b input_file.dat' command is not the same.
The output I am expecting is (generated with C type IO code)
0000000: 00101010 00000000 00000000 00000000 *...
But I see (generated with my attempt of C++ type IO code)
0000000: 00100000 00100000 00110100 00110010 42
Looking for a solution. Appreciate the help!
Upvotes: 0
Views: 563
Reputation: 141900
Use ostream::write
.
myFile.write(reinterpret_cast<char*>(&magicn), sizeof(magicn));
Upvotes: 1
Reputation: 385385
Your current approach is more like fprintf(myFile, "%d", magicn)
. That is, it performs formatted insertion to the stream, so you end up with the ASCII code for the 42nd ASCII character.
The analogue of fwrite
is ostream::write
. Just look at the available members of ostream
to find out what you can do with it.
Upvotes: 2