在C中读写二进制文件? [英] Read and write to binary files in C?
问题描述
任何人都有可以写入二进制文件的代码示例.以及可以读取二进制文件并输出到屏幕的代码.看例子,我可以写文件了,但是当我尝试从文件中读取文件时,它不能正确输出.
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
嗯,也许将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屋!