How do you read binary files in the C language?

In the C language, you can open a binary file using the fopen function and read the file content using the fread function.

#include <stdio.h>

int main() {
    FILE *file;
    char buffer[100];
    
    file = fopen("example.bin", "rb"); // 打开二进制文件
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }
    
    fread(buffer, sizeof(char), 100, file); // 读取文件内容到buffer中
    
    printf("File content: %s\n", buffer);
    
    fclose(file); // 关闭文件
    
    return 0;
}

In the example above, we first open a binary file named “example.bin” using the fopen function and specifying the mode as “rb” (which means opening a binary file in read-only mode). Then we use the fread function to read 100 bytes of content from the file into a buffer. Finally, we use the printf function to print out the content read from the file. Lastly, we close the file using the fclose function.

bannerAds