What is perror() in C++?
The perror() function displays the description of the error that corresponds to an error code stored in the system variable errno.
errnois a system variable which holds the error code that describes the error condition. This error condition is produced by a call to a library function.
Syntax
Input
str: The pointer to a null-terminated string. This string should contain an explanatory message about the error.
Code
The perror() function outputs the error description by combining the following in the given order:
- The contents of the string pointed to by
str. - The character “:”.
- The error message corresponding to the error code in the variable
errno.
#include <stdio.h>int main () {FILE *fp;/* If we try to open a file that does not existthe variable errno will be set accordingly. */fp = fopen("file.txt", "r");if( fp == NULL ) {// The following string is prepended to the error description.perror("The error is ");return(-1);}fclose(fp);return(0);}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved