简体   繁体   English

在C中打开二进制文件

[英]Opening binary files in C

I'm trying to open a binary file and read the contents for a class assignment. 我正在尝试打开一个二进制文件并读取类分配的内容。 Even after doing research, I'm having trouble getting anything to appear while attempting open and prints contents of a binary file. 即使经过研究,在尝试打开并打印二进制文件的内容时,我仍然无法显示任何内容。 I'm not even sure what I should be getting, how to check that it's right but I know that nothing (which is what I'm currently getting) is bad. 我什至不确定我应该得到什么,如何检查是否正确,但是我知道没有什么(这就是我目前正在得到的)是不好的。 Here's the code I got from searching on this site 这是我在该网站上搜索得到的代码

#include<stdio.h>

int main()
{
    FILE *ptr_myfile;
    char buf[8];

    ptr_myfile = fopen("packets.1","rb");
    if (!ptr_myfile)
    {
        printf("Unable to open file!");
        return 1;
    }

    fread(buf, 1, 8, ptr_myfile);

    printf("First Character: %c", buf[0]);

    fclose(ptr_myfile);
    return 0;
}

When this prints, I get "First Character: " with nothing else printed. 打印此文件时,我得到的“第一个字符:”未打印任何其他内容。 Maybe it doesn't print normally in terminal? 也许在终端上无法正常打印? I'm not sure, any help would be greatly appreciated, thanks 我不确定,任何帮助将不胜感激,谢谢

First, you need to check how much data you have in the buffer. 首先,您需要检查缓冲区中有多少数据。 fread returns length; fread返回长度; if it is zero, accessing buf[0] is not legal. 如果为零,则访问buf[0]是不合法的。

Not all characters are printable You can see what data you are getting if you print the character code of c , rather than c itself. 并非所有字符都可以打印如果您打印c的字符代码,而不是c本身,则可以看到要获取的数据。 Use %d for that. 为此使用%d

size_t len = fread(buf, 1, 8, ptr_myfile);
if (len != 0) {
    printf("First Character: '%c', code %d", buf[0], buf[0]);
} else {
    printf("The file has no data\n");
}

If it's a binary file, it's very likely that its contents don't print particularly well as text (that's what makes a binary a binary file). 如果它是二进制文件,则其内容很可能打印得不如文本特别好(这就是使二进制文件成为二进制文件的原因)。 Instead of printing as characters try printing as hexadecimal numbers: 而不是打印为字符,请尝试打印为十六进制数字:

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

int main()
{
    FILE *ptr_myfile;
    char buf[8];

    ptr_myfile = fopen("packets.1","rb");
    if (!ptr_myfile)
    {
        printf("Unable to open file!");
        return 1;
    }

    size_t rb;
    do {
        rb = fread(buf, 1, 8, ptr_myfile);
        if( rb ) {
            size_t i;
            for(i = 0; i < rb; ++i) {
                    printf("%02x", (unsigned int)buf[i]);
            }
            printf("\n");
        }
     } while( rb );

    fclose(ptr_myfile);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM