B0RDERS
B0RDERS

Reputation: 217

Write a character array with null values into a file stream

I am new to c++ and am still figuring out file streams. I am trying to put a character array into a file that I will be viewing with a hex editor.

I have done different strings, but whenever I put in a null byte, the file ends.

ofstream stream;
char charArray[256];
for (int i = 0; i <= 255; i++)charArray[i] = i;
stream.open("C:\\testfile.myimg");
if (!stream.is_open()) exit(1);
stream << charArray << endl;
return 0;

I want to output bytes with ascending values, but if I start with the null byte, then c++ thinks the character array ends before it starts

Upvotes: 0

Views: 800

Answers (1)

Fureeish
Fureeish

Reputation: 13434

Instead of:

stream << charArray << endl;

use:

stream.write(charArray, sizeof(charArray));
stream.write("\n", 1);  // this is the newline part of std::endl
stream.flush();         // this is the flush part of std::endl

The first one assumes that you are sending a null-terminated string (because you're passing a char* - see the end of the answer why). That's why when the code encounters the very first char with value 0, which is '\0' (the null-terminator), it stops.

On the other hand, the second approach uses an unformatted output write, which will not care about the values inside charArray - it will take it (as a pointer to its first element) and write sizeof(charArray) bytes starting from that pointer to the stream. This is safe since it's guaranteed that sizeof(char) == 1, thus sizeof(charArray) will yield 256.

What you need to consider is array decaying. It will work in this case (the sizeof thing), but it will not work if you simply pass a decayed pointer to the array's first element. Read more here: what's array decaying?

Upvotes: 2

Related Questions