開啟並寫入二進位制檔案

#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;  
}

其他函式遵循相同的模式,對大小和位元組順序進行微小修改。