C 庫函數 - strerror()

C 標準庫 - <string.h> C 標準庫 - <string.h>

描述

C 庫函數 char *strerror(int errnum) 從內部數組中搜索錯誤號 errnum,並返回一個指向錯誤消息字串的指針。strerror 生成的錯誤字串取決於開發平臺和編譯器。

聲明

下麵是 strerror() 函數的聲明。

char *strerror(int errnum)

參數

  • errnum -- 錯誤號,通常是 errno

返回值

該函數返回一個指向錯誤字串的指針,該錯誤字串描述了錯誤 errnum。

實例

下麵的實例演示了 strerror() 函數的用法。

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main ()
{
   FILE *fp;

   fp = fopen("file.txt","r");
   if( fp == NULL )
   {
      printf("Error: %s\n", strerror(errno));
   }

  return(0);
}

讓我們編譯並運行上面的程式,這將產生以下結果,因為我們嘗試打開一個不存在的檔:

Error: No such file or directory

C 標準庫 - <string.h> C 標準庫 - <string.h>