读/写在C二进制文件 [英] Read/Write to binary files in C
问题描述
有没有人有code的一个例子,可以写一个二进制文件。也code,可以读取一个二进制文件并输出到屏幕上。看着例子,我可以写一个文件就OK了但是当我尝试从没有正确输出文件中读取。
Does anyone have an example of code that can write to a binary file. And also code that can read a binary file and output to screen. Looking at examples I can write to a file ok But when I try to read from a file it is not outputting correctly.
推荐答案
读取和写入二进制文件是pretty大致相同的任何其他文件,唯一的区别是如何打开它:
Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:
unsigned char buffer[10];
FILE *ptr;
ptr = fopen("test.bin","rb"); // r for read, b for binary
fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer
您说您能读它,但它无法正常输出......请记住,当你输出这个数据,你不读ASCII,所以它不是像打印字符串到屏幕上:
You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:
for(int i = 0; i<10; i++)
printf("%u ", buffer[i]); // prints a series of bytes
写入一个文件是pretty大致相同,与你使用的 的fwrite()
而不是 FREAD()
:
FILE *write_ptr;
write_ptr = fopen("test.bin","wb"); // w for write, b for binary
fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer
由于我们正在谈论的Linux ..有一个简单的方法做一个全面的检查。在系统上安装 hexdump都
(如果它不是已经在那里)和转储文件:
Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump
on your system (if it's not already on there) and dump your file:
mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...
现在比较,为您的输出:
Now compare that to your output:
mike@mike-VirtualBox:~/C$ ./a.out
127 69 76 70 2 1 1 0 0 0
嗯,也许改变的printf
到%X
来使这一点更为清晰:
hmm, maybe change the printf
to a %x
to make this a little clearer:
mike@mike-VirtualBox:~/C$ ./a.out
7F 45 4C 46 2 1 1 0 0 0
嘿,看!数据现在相匹配 * 。真棒,我们必须正确地读取二进制文件!
Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!
*注意字节只是交换的输出,但这些数据是正确的,你可以调整这样的事情
这篇关于读/写在C二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!