本文介绍了什么是二进制文件,我如何创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个二进制文件重新presenting一个整数。我认为该文件应为4个字节。我使用Linux操作系统。怎么做?
另外一个问题:我如何该文件的内容分配到一个整数用C

I would like to create a binary file representing an integer. I think the file should be 4 bytes. I use linux. How to do that?Another question: How do I assign the content of that file to an integer in C?

推荐答案

在标准C, fopen()函数允许模式WB写(和RB阅读)以二进制方式,即:

In standard C, fopen() allows the mode "wb" to write (and "rb" to read) in binary mode, thus:

#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

这篇关于什么是二进制文件,我如何创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:15