简体   繁体   English

用 C 将一个字节写入文件

[英]Write a byte to a file in C

I have a byte declared as unsigned int 0b11010101 how can I write this to a binary file as 1 byte?我有一个字节声明为unsigned int 0b11010101如何将它作为 1 个字节写入二进制文件? I know fwrite takes type const void * as a buffer but I don't know how to write my byte if it's represented as an unsigned int.我知道 fwrite 将类型const void *作为缓冲区,但如果它表示为无符号整数,我不知道如何写入我的字节。

Perhaps like this, you better not write one byte of an int because of endianness.也许像这样,由于字节顺序,你最好不要写一个int字节。 Convert to unsigned char first.首先转换为unsigned char

unsigned int intval = 0b11010101;       // assuming compiler likes it
unsigned char charval = intval;
fwrite (&charval, 1, 1, stream);

You can write a single byte to a file using fputc() .您可以使用fputc()将单个字节写入文件。

Example:例子:

unsigned int val = 0b11010101;
fputc(val, stream);

Tested using:测试使用:

~ $ cc -Wall -o test test.c
~ $ ./test | xxd
00000000: d5                                       .

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

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