S.H.
S.H.

Reputation: 211

can't write correctly large unsigned ints to binary file - c++

In my project i need to write to a binary file sequential unsigned ints, and it's important that each number takes exact 4 bytes. But when i open the binary file with a hex editor, i see this strange happening: the numbers are written correctly just up to number 9; before number 10 he will add another extra byte and write '13' (and already messed up with my file). And strange things continue to happen- from number 30 and on will be written different characters, one aside each number. why is that? how to fix, at least the size issue? Here is my simple sample code:

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out);
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();

    return 0;
}

and is attached an image of what i see in the file: file capture on hex editor

thanks

Upvotes: 0

Views: 68

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The number 10 is a newline character LF, and it is converted to CRLF because the file is opened in text mode.

Open files in binary mode to deal with binary files.

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

using std::string;
using std::cin;
using std::fstream;
using std::ios;

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out | ios::binary); // add OR with ios::binary
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();
}

Upvotes: 1

Related Questions