C++ 程式設計/程式碼/標準 C 庫/函式/perror
外觀
| 語法 |
#include <cstdio>
void perror( const char *str );
|
perror() 函式將 str、一個 ":" 後跟一個空格、一個與全域性變數 errno 相對應的實現定義和/或語言相關的錯誤訊息以及一個換行符寫入 stderr。例如
char* input_filename = "not_found.txt";
FILE* input = fopen( input_filename, "r" );
if( input == NULL ) {
char error_msg[255];
sprintf( error_msg, "Error opening file '%s'", input_filename );
perror( error_msg );
exit( -1 );
}
如果名為 not_found.txt 的檔案未找到,則此程式碼將產生以下輸出
Error opening file 'not_found.txt': No such file or directory
如果 "str" 是一個空指標或指向空位元組,則只會將與 errno 相對應的錯誤訊息和一個換行符寫入 stderr。