Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a file byte by byte using c++

Tags:

c++

How to write a file byte by byte using c++?

unsigned short array[2]={ox20ac,0x20bc};

if i have a hexadecimal value 0x20ac how can i write it byte by byte in a file using c++

like image 878
Venkatesan Avatar asked Dec 05 '13 12:12

Venkatesan


2 Answers

You can try something like this:

#include <fstream>
...

ofstream fout;
fout.open("file.bin", ios::binary | ios::out);

int a[4] = {100023, 23, 42, 13};
fout.write((char*) &a, sizeof(a));

fout.close();
like image 176
yasen Avatar answered Nov 05 '22 23:11

yasen


One option, using standard C++ library:

#include <fstream>
#include <assert.h>

void main()
{
    unsigned short array[2]={ox20ac,0x20bc};

    std::ofstream file;
    file.open("C:/1.dat", std::ios_base::binary);
    assert(file.is_open());

    for(int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
       file.write((char*)(array + i * sizeof(array[0])), sizeof(array[0]));
    file.close();
}

Alternatively, you can easily write your whole data in one go (without a loop):

file.write((const char*)array, sizeof(array));

like image 6
Violet Giraffe Avatar answered Nov 05 '22 22:11

Violet Giraffe