9

I have a char type array[100] with 100 bytes stored in it. I want to write this char type byte array to a file. How could I do this?

I am not writing to a .txt file but some other format.

Thank you.

1
  • 1
    It'll depend on the format. If you just want to copy the array into the file in binary format, ofstream::write would be the obvious choice. Commented Jun 28, 2012 at 17:29

3 Answers 3

33

Some people object to using <cstdio>, so it is worth mentioning how one might use <fstream>:

{
  std::ofstream file("myfile.bin", std::ios::binary);
  file.write(data, 100);
}

The four lines above could be combined into this single line:

std::ofstream("myfile.bin", std::ios::binary).write(data, 100);
Sign up to request clarification or add additional context in comments.

Comments

18

No need to get complicated. Just use good old fwrite directly:

FILE* file = fopen( "myfile.bin", "wb" );
fwrite( array, 1, 100, file );

1 Comment

-1: This is inferior to the ofstream-based answers provided elsewhere in this topic. It is certainly not less complicated and it is not type safe. And it contains an error (you don't close the file).
5

Based on the (little) information you've provided, one possibility would be to write the array to the file in binary format, such as:

std::ofstream out("somefile.bin", std::ios::binary);
out.write(array, sizeof(array));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.