- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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.
廣告