问题描述
谁有可以写入二进制文件的代码示例.还有可以读取二进制文件并输出到屏幕的代码.查看示例我可以写入文件,但是当我尝试从文件中读取时,它没有正确输出.
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.
推荐答案
二进制文件的读写与其他文件几乎相同,唯一的区别在于打开方式:
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
写入文件几乎相同,除了您使用的是 fwrite()
而不是 fread()
:
Writing to a file is pretty much the same, with the exception that you're using fwrite()
instead of 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
hmm,也许将 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读写二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!