简体   繁体   English

将uint8_t类型写入文件C ++

[英]write uint8_t type to a file C++

I have a pointer of type uint8_t *ptr type, that is pointing to a some 32 bytes of binary data. 我有一个类型为uint8_t * ptr类型的指针,指向大约32字节的二进制数据。 I would like to print the content that my pointer is pointing to , to a file in C++. 我想将我的指针指向的内容打印到C ++中的文件。 I am going with the binary mode ie 我正在使用二进制模式即

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. 有没有办法可以这样做,以便我打印出ptr指向的内容,因为我刚刚显示的方式,当它指向32字节的数据时,我在文件中获得8个字节的数据。

You get 8 bytes because the pointer on your computer is 64-bit. 你得到8个字节,因为你的计算机上的指针是64位。 Hence, sizeof(ptr) returns 8 -- you get the size of the pointer, not the size of the array. 因此, sizeof(ptr)返回8 - 您获得指针的大小,而不是数组的大小。 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);
}
double pi = 3.1415926535; // IEEE 8 bytes
uint8_t bytes[8] = { 0 };
double* dp = (double*)(&bytes[0]); //force dp to point to bytes
*dp = pi; // copies pi into bytes
file.write((char*)dp,sizeof(bytes));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM