简体   繁体   中英

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.

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

However, when I tried using memcpy() to a string,

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

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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