C:从二进制文件读取字节

格雷格

我目前正在尝试从二进制文件读取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;
}
戴维·C·兰金

的基本用法fread将对照预期的字节数检查返回值,以验证您已阅读了要阅读的内容。保存返回值还可以处理部分读取。

下面的最小示例一次从作为第一个参数给出的文件中读取16个字节(stdin如果没有给出文件,则默认情况下)读取到16字节,buf然后将每个值输出为16stdout进制格式。

#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;
}

(注意:bytes == readsz只有当size参数fread1该回报是多少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

查看示例,让我知道是否有任何问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章