C++ perror()

The perror() function in C++ prints the error message to stderr based on the error code currently stored in the system variable errno.

perror() prototype

void perror(const char* str);

The perror() function interprets the value of errno to print an error message to stderr. errno holds an integer value which determines the error condition.

The error message is formed by concatenating the following components:

  • Content of the string pointed to by str.
  • A colon i.e. ':'.
  • Error message describing the error code stored in errno.
  • A newline character i.e. '\n'.

It is defined in <cstdio> header file.

perror() Parameters

str: Pointer to a null terminated string.

perror() Return value


Example: How perror() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
    char filename[] = "example.txt";
/* if the file can not be reomved */    
if (remove(filename) != 0)
        perror("File deletion failed");
        cout << "File deleted successfully";
    return 0;

If the file is not present running the program will produce:

File deletion failed: No such file or directory
Did you find this article helpful?