C 庫 - ferror() 函式



C 庫的 ferror(FILE *stream) 函式用於測試給定流的錯誤指示器。在處理檔案操作時,瞭解可能發生的任何錯誤非常重要,因為它們可能導致資料損壞、崩潰或未定義的行為。ferror 函式有助於檢測此類錯誤。

語法

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

int ferror(FILE *stream);

引數

  • FILE *stream: 指向 FILE 物件的指標,用於標識要檢查錯誤的流。此流通常來自 fopen 等函式。

返回值

如果指定流發生錯誤,則 ferror 函式返回非零值。如果未發生錯誤,則返回 0。

示例 1:寫入檔案後檢查錯誤

此示例嘗試將一些文字寫入檔案。寫入後,它使用 ferror 檢查是否發生任何錯誤。

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

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   fputs("Hello, World!", file);

   if (ferror(file)) {
       printf("An error occurred while writing to the file.\n");
   } else {
       printf("Writing to the file was successful.\n");
   }

   fclose(file);
   return 0;
}

輸出

以上程式碼產生以下結果:

Writing to the file was successful.

示例 2:透過過早關閉檔案強制發生錯誤

在此示例中,我們透過關閉檔案然後嘗試寫入檔案來強制發生錯誤。它使用 ferror 檢查錯誤。

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   fputs("This is a test.", file);

   fclose(file);

   // Attempt to write to the closed file
   fputs("This will cause an error.", file);

   if (ferror(file)) {
       printf("An error occurred because the file was already closed.\n");
   } else {
       printf("Writing to the file was successful.\n");
   }

   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

An error occurred because the file was already closed.
廣告

© . All rights reserved.