Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a byte type char array data to a file in c++? [closed]

Tags:

c++

arrays

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.

like image 406
user1486008 Avatar asked Jun 28 '12 17:06

user1486008


2 Answers

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);
like image 94
Robᵩ Avatar answered Oct 20 '22 22:10

Robᵩ


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

FILE* file = fopen( "myfile.bin", "wb" );
fwrite( array, 1, 100, file );
like image 22
Rafael Baptista Avatar answered Oct 20 '22 22:10

Rafael Baptista