C 庫 - setvbuf() 函式



C 庫的 setvbuf() 函式用於控制檔案流的緩衝。此函式可以設定緩衝模式,並可選地為流指定緩衝區。

語法

以下是 C 庫 setvbuf() 函式的語法:

int setvbuf(FILE *stream, char *buffer, int mode, size_t size);

引數

此函式接受以下引數:

  • stream: 指向 FILE 物件的指標,用於標識開啟的檔案流。
  • buffer: 指向將用作緩衝區的字元陣列的指標。如果 buffer 為 NULL,則函式將自動分配緩衝區。
  • mode: 指定緩衝模式的整數。它可以是以下之一:
    • _IOFBF: 全緩衝。當緩衝區滿時寫入資料。
    • _IOLBF: 行緩衝。當遇到換行符時寫入資料。
    • _IONBF: 無緩衝。立即寫入資料。
  • size: 緩衝區的大小(以位元組為單位)。如果 buffer 為 NULL,則忽略此引數。

返回值

函式成功返回 0,失敗返回非零值。

示例 1:使用自定義緩衝區的全緩衝

在這裡,我們為全緩衝設定了一個大小為 1024 位元組的自定義緩衝區。當緩衝區滿或檔案關閉時,資料將寫入檔案。

以下是 C 庫 setvbuf() 函式的示例。

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (!file) {
       perror("Failed to open file");
       return 1;
   }

   char buffer[1024];
   if (setvbuf(file, buffer, _IOFBF, sizeof(buffer)) != 0) {
       perror("Failed to set buffer");
       return 1;
   }

   fputs("This is a test string.", file);
   fclose(file);
   return 0;
}

輸出

以上程式碼在檔案關閉時將“This is a test string.”寫入 example1.txt。

This is a test string.

示例 2:無緩衝

此示例停用緩衝,這意味著資料將立即寫入檔案。

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (!file) {
       perror("Failed to open file");
       return 1;
   }

   if (setvbuf(file, NULL, _IONBF, 0) != 0) {
       perror("Failed to set buffer");
       return 1;
   }

   fputs("This is a test string.", file);
   fputs("This is another string.", file);
   fclose(file);
   return 0;
}

輸出

執行以上程式碼後,它會立即將“This is a test string.This is another string.”寫入 example3.txt,因為每次 fputs 呼叫都會進行寫入。

This is a test string.This is another string.
廣告