跳轉到內容

C 程式設計/stdio.h/perror

來自華夏公益教科書,自由的教科書

POSIX 錯誤函式 perror 用於 C 和 C++ 中,根據儲存在 errno 中的錯誤狀態,向 stderr 列印錯誤訊息。[1] 它列印 str 和與全域性變數 errno 對應的實現定義的錯誤訊息。

perror 的定義首次釋出在 System V 介面定義的第 1 版中。

#include <stdio.h>
void perror(const char* prefix);
int fd = open("/etc/passwd", O_RDONLY);
if (fd == -1) {
    perror("open");
    exit(1); 
}

如果引數 prefix 不是 NULL,perror 將首先列印 prefix,後跟一個冒號和一個空格到標準錯誤。然後,它會列印 strerror 的結果到標準錯誤,後跟一個換行符。例如,上面的示例可能會列印

open: Permission denied

參考文獻

[編輯 | 編輯原始碼]
  1. ISO/IEC 9899:1999 規範 (PDF). p. 305, § 7.19.10.2.
[編輯 | 編輯原始碼]
華夏公益教科書