c - 什么是二进制文件,我该如何创建?

标签 c linux binaryfiles

我想创建一个表示整数的二进制文件。我认为该文件应该是 4 个字节。我使用Linux。怎么做? 另一个问题:如何将该文件的内容分配给 C 中的整数?

最佳答案

在标准 C 中,fopen() 允许模式 "wb" 以二进制模式写入(和 "rb" 读取) ,因此:

#include <stdio.h>

int main() {
    /* Create the file */
    int x = 1;
    FILE *fh = fopen ("file.bin", "wb");
    if (fh != NULL) {
        fwrite (&x, sizeof (x), 1, fh);
        fclose (fh);
    }

    /* Read the file back in */
    x = 7;
    fh = fopen ("file.bin", "rb");
    if (fh != NULL) {
        fread (&x, sizeof (x), 1, fh);
        fclose (fh);
    }

    /* Check that it worked */
    printf ("Value is: %d\n", x);

    return 0;
}

这个输出:

Value is: 1

关于c - 什么是二进制文件,我该如何创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/979816/

相关文章:

c - 如何解决2+2和2++2冲突

c - 搜索并删除字符数组

python - 如何交叉编译Python?

php - 是否可以使用PHP生成WAV文件?

c - 编译时出错

c - SDL_GetKeyboardState 不起作用

php - 创建目录的正确权限是什么?

linux - 将输出存储到变量 bash

excel - 了解二进制 xls 文件格式

windows - 是否可以使用 Windows 命令行编辑二进制文件?