Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write uint8_t type to a file C++

Tags:

c++

file-io

I have a pointer of type uint8_t *ptr type, that is pointing to a some 32 bytes of binary data. I would like to print the content that my pointer is pointing to , to a file in C++. I am going with the binary mode i.e

ofstream fp;
fp.open("somefile.bin",ios::out | ios :: binary );
//fp.write( here is the problem )
fp.write((char*)ptr,sizeof(ptr));

Is there a way I can do it so that I print out the contents that ptr is pointing to because the way I have just shown, I get 8 bytes of data in the file while it is pointing to 32 bytes of data.

like image 950
Swair Mehta Avatar asked Dec 16 '22 21:12

Swair Mehta


1 Answers

You get 8 bytes because the pointer on your computer is 64-bit. Hence, sizeof(ptr) returns 8 -- you get the size of the pointer, not the size of the array. You should be passing the size of the data to write alongside the pointer, for example, like this:

uint8_t data[32];
// fill in the data...
write_to_file(data, sizeof(data));

void write_to_file(uint8_t *ptr, size_t len) {
    ofstream fp;
    fp.open("somefile.bin",ios::out | ios :: binary );
    fp.write((char*)ptr, len);
}
like image 66
Sergey Kalinichenko Avatar answered Dec 31 '22 07:12

Sergey Kalinichenko