0

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

B0RDERS
  • 217
  • 1
  • 8

1 Answers1

2

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?

Fureeish
  • 12,533
  • 4
  • 32
  • 62
  • You should also open the file in `binary` mode when writing raw data to it. – Remy Lebeau Jul 03 '19 at 21:27
  • @RemyLebeau I totally see why that would be a logical assumption, but I'm struggling to actually find sources saying that it won't work without opening in binary mode. Would you please provide a standard section regarding this very case or some other, reliable source? – Fureeish Jul 03 '19 at 21:33