博客專欄

EEPW首頁 > 博客 > 嵌入式Linux:strerror函數(shù)和perror函數(shù)

嵌入式Linux:strerror函數(shù)和perror函數(shù)

發(fā)布人:美男子玩編程 時(shí)間:2024-06-21 來源:工程師 發(fā)布文章

strerror函數(shù)和perror函數(shù)是C標(biāo)準(zhǔn)庫(kù)中的兩個(gè)函數(shù),用于處理和顯示錯(cuò)誤信息。它們幫助程序員在程序運(yùn)行過程中了解并診斷錯(cuò)誤原因。


strerror函數(shù),返回錯(cuò)誤消息字符串,需要程序員自己調(diào)用printf等函數(shù)來打印錯(cuò)誤消息。更加靈活,可以組合其他字符串一起使用。


perror函數(shù),直接打印錯(cuò)誤消息,適合簡(jiǎn)單的錯(cuò)誤報(bào)告。不需要額外的printf調(diào)用。



1


strerror函數(shù)


strerror函數(shù)將錯(cuò)誤代碼轉(zhuǎn)換為相應(yīng)的錯(cuò)誤消息字符串。其原型為:




char *strerror(int errnum);



參數(shù):


  • errnum:錯(cuò)誤代碼,通常是全局變量errno的值。


返回值:


  • 返回指向描述錯(cuò)誤的字符串的指針。



在以下示例中,嘗試打開一個(gè)不存在的文件會(huì)導(dǎo)致fopen失敗,errno被設(shè)置為相應(yīng)的錯(cuò)誤代碼。strerror(errno)將該錯(cuò)誤代碼轉(zhuǎn)換為一個(gè)描述錯(cuò)誤的字符串并打印出來。














#include#include#include
int main() {    FILE *file = fopen("nonexistent.txt", "r");    if (file == NULL) {        printf("Error opening file: %sn", strerror(errno));    }    return 0;}

2


perror函數(shù)


perror函數(shù)直接打印一條描述錯(cuò)誤的消息,錯(cuò)誤信息包括由errno指定的錯(cuò)誤描述。其原型為:




void perror(const char *s);



參數(shù):


  • s:一個(gè)用戶提供的前綴字符串,如果非空,則首先打印該字符串,然后打印一個(gè)冒號(hào)和空格,再打印錯(cuò)誤消息。


返回值:


  • 無返回值。



在以下示例中,perror函數(shù)輸出的消息包括用戶提供的前綴字符串和錯(cuò)誤描述。



#include#include
int main() {    FILE *file = fopen("nonexistent.txt", "r");    if (file == NULL) {        perror("Error opening file");    }    return 0;}


例如,如果文件不存在,輸出可能是:


Error opening file: No such file or directory



*博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。



關(guān)鍵詞: 嵌入式 Linux

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉