Latest web development tutorials

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>