简体   繁体   English

关于字节大小的write()和memcpy()之间的区别

[英]Difference between write() and memcpy() with regards to the size of bytes

I'm currently trying to recover image data, but instead of writing it into a text file before recovering, I would like to put them into database.. Now, i write 4 byte(starting cluster), 2byte(header), 2byte(data) into a text file. 我目前正在尝试恢复图像数据,但不是在恢复之前将其写入文本文件,而是将它们放入数据库中。现在,我写入4字节(起始集群),2字节(标题),2字节(数据)到文本文件中。

DWORD x = 0;
WORD headerByte = 0;
WORD dataByte = 0;

write(jpg_info,&x,4);
write(jpg_info,&headerByte,2);
write(jpg_info,&dataByte,2);

My outcome after opening the jpg_info.txt will be(for example): DB 21 00 00 95 05 00 00 打开jpg_info.txt后的结果将是(例如):DB 21 00 00 95 05 00 00

However, when I tried using memcpy() to a string, 但是,当我尝试将memcpy()用于字符串时,

char xChar[8];
char headerByteChar[4];
char dataByteChar[4];

memcpy(xChar, &x, 4);
memcpy(headerByteChar, &headerByte, 2);
memcpy(dataByteChar, &dataByte, 2);

My outcome will be: DB 21 95 05 我的结果将是:DB 21 95 05

Which is not what I want.. I tried various methods, but I could never get the same results.. 这不是我想要的..我尝试了各种方法,但我永远得不到相同的结果..

As x is only using 2 bytes of data, I would like to have the remaining 2bytes to be 00 even it only occupies 2byte of data. 由于x只使用2个字节的数据,我希望剩余的2个字节为00,即使它只占用2个字节的数据。

Is there anyway to do so? 反正有没有这样做?

Sorry, i've been stuck here for weeks! 对不起,我已经被困在这里好几个星期了!

The zero byte is interpreted as the string termination character by most C apis. 大多数C apis将零字节解释为字符串终止字符。 What's happening here is that memcpy does copy the zero byte into the character array, but whatever you're using to process the arrays later stops at the first zero byte. 这里发生的是memcpy将零字节复制到字符数组中,但是无论你用什么来处理数组,都会在第一个零字节处停止。

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

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