C 庫函數(shù) - perror()

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

描述

C 庫函數(shù) void perror(const char *str) 把一個描述性錯誤消息輸出到標準錯誤 stderr。首先輸出字符串 str,后跟一個冒號,然后是一個空格。

聲明

下面是 perror() 函數(shù)的聲明。

void perror(const char *str)

參數(shù)

  • str -- 這是 C 字符串,包含了一個自定義消息,將顯示在原本的錯誤消息之前。

返回值

該函數(shù)不返回任何值。

實例

下面的實例演示了 perror() 函數(shù)的用法。

#include <stdio.h>

int main ()
{
   FILE *fp;

   /* 首先重命名文件 */
   rename("file.txt", "newfile.txt");

   /* 現(xiàn)在讓我們嘗試打開相同的文件 */
   fp = fopen("file.txt", "r");
   if( fp == NULL ) {
      perror("Error: ");
      return(-1);
   }
   fclose(fp);
      
   return(0);
}

讓我們編譯并運行上面的程序,這將產(chǎn)生以下結果,因為我們嘗試打開一個不存在的文件:

Error: : No such file or directory

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