Gre*_*egH 5 c binary fopen fread
我目前正在尝试从二进制文件读取 256 个字节,但在运行程序时没有得到任何输出(或错误)。我有点困惑我在这件事上哪里出错了。尝试将每个读取byte
为 achar
并将其存储为长度为 256 的 char 数组。我已经审查了有关 SO 的类似问题,但到目前为止还没有任何运气。我的代码的简化版本如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *binary = fopen(argv[1], "rb");
char bytesFromBinary[256];
fread(&bytesFromBinary, 1, 256, binary);
printf("%s", bytesFromBinary);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
的基本用法fread
将检查返回的预期字节数,以验证您读取了您想要读取的内容。保存返回还可以让您处理部分读取。
以下最小示例一次从作为第一个参数给出的文件(如果stdin
没有给出文件则默认)读取16 个字节buf
,然后以stdout
十六进制格式输出每个值。
#include <stdio.h>
#define BUFSZ 16
int main (int argc, char **argv) {
unsigned char buf[BUFSZ] = {0};
size_t bytes = 0, i, readsz = sizeof buf;
FILE *fp = argc > 1 ? fopen (argv[1], "rb") : stdin;
if (!fp) {
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
/* read/output BUFSZ bytes at a time */
while ((bytes = fread (buf, sizeof *buf, readsz, fp)) == readsz) {
for (i = 0; i < readsz; i++)
printf (" 0x%02x", buf[i]);
putchar ('\n');
}
for (i = 0; i < bytes; i++) /* output final partial buf */
printf (" 0x%02x", buf[i]);
putchar ('\n');
if (fp != stdin)
fclose (fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(注:bytes == readsz
仅当size
参数为fread
时1
,返回的是读取的次数items
,且每一项仅等于1
类型char
值)
使用/输出示例
$ echo "A quick brown fox jumps over the lazy dog" | ./bin/fread_write_hex
0x41 0x20 0x71 0x75 0x69 0x63 0x6b 0x20 0x62 0x72 0x6f 0x77 0x6e 0x20 0x66 0x6f
0x78 0x20 0x6a 0x75 0x6d 0x70 0x73 0x20 0x6f 0x76 0x65 0x72 0x20 0x74 0x68 0x65
0x20 0x6c 0x61 0x7a 0x79 0x20 0x64 0x6f 0x67 0x0a
Run Code Online (Sandbox Code Playgroud)
查看示例,如果您有任何疑问,请告诉我。