打开并写入二进制文件

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

int main(void)
{
   result = EXIT_SUCCESS;

   char file_name[] = "outbut.bin";
   char str[] = "This is a binary file example";
   FILE * fp = fopen(file_name, "wb");
   
   if (fp == NULL)  /* If an error occurs during the file creation */
   {
     result = EXIT_FAILURE;
     fprintf(stderr, "fopen() failed for '%s'\n", file_name);
   }
   else
   {
     size_t element_size = sizeof *str;
     size_t elements_to_write = sizeof str;

     /* Writes str (_including_ the NUL-terminator) to the binary file. */
     size_t elements_written = fwrite(str, element_size, elements_to_write, fp); 
     if (elements_written != elements_to_write)
     {
       result = EXIT_FAILURE;
       /* This works for >=c99 only, else the z length modifier is unknown. */
       fprintf(stderr, "fwrite() failed: wrote only %zu out of %zu elements.\n", 
         elements_written, elements_to_write);
       /* Use this for <c99: *
       fprintf(stderr, "fwrite() failed: wrote only %lu out of %lu elements.\n", 
         (unsigned long) elements_written, (unsigned long) elements_to_write);
        */
     }

     fclose(fp);
   }

   return result;
}

该程序通过 fwrite 函数创建二进制形式的文本并将其写入文件 output.bin

如果已存在具有相同名称的文件,则会丢弃其内容,并将该文件视为新的空文件。

二进制流是一个有序的字符序列,可以透明地记录内部数据。在此模式下,在程序和文件之间写入字节而不进行任何解释。

要以便携式方式编写整数,必须知道文件格式是否需要大端或小端格式以及大小(通常为 16,32 或 64 位)。然后可以使用比特移位和屏蔽以正确的顺序写出字节。C 中的整数不保证有两个补码表示(尽管几乎所有实现都有)。所幸无符号转换保证使用二进制补码。因此,将有符号整数写入二进制文件的代码有点令人惊讶。

/* write a 16-bit little endian integer */
int fput16le(int x, FILE *fp)
{
    unsigned int rep = x;
    int e1, e2;

    e1 = fputc(rep & 0xFF, fp);
    e2 = fputc((rep >> 8) & 0xFF, fp);

    if(e1 == EOF || e2 == EOF)
        return EOF;
    return 0;  
}

其他函数遵循相同的模式,对大小和字节顺序进行微小修改。