将uint8_t类型写入文件C++

Swa*_*hta 2 c++ file-io

我有一个类型为uint8_t*ptr类型的指针,它指向大约32字节的二进制数据.我想将我的指针指向的内容打印到C++中的文件.我正在使用二进制模式即

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

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

das*_*ght 8

你得到8个字节,因为你的计算机上的指针是64位.因此,sizeof(ptr)返回8 - 您获得指针的大小,而不是数组的大小.您应该传递数据的大小以与指针一起写入,例如,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)