Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use perror() in C++

Sadia Zubair

The perror() function prints the description of the error to the standard error output stream that corresponds to an error code saved in the system variable errno.

The errno variable is of type int – its value describes the error condition that occurs in the code.

No special library needs to be added in the code to use the perror function.

Figure 1 : Function declaration

Parameters

The function takes in one parameter, the pointer to a string. If the parameter is not a null pointer, then the custom message is followed by a colon and space; else, only the error messagecorresponds to the error code in the erno variable is printed.

Return value

The perror function has a return type of void, so it has no return value.

Example

The code below tries to open a file with the name “demo.txt”. Since no such file exists in the directory, an error is raised. In line 9, The custom message added in the perror function is “Error”. When the program runs, “Error” is printed, followed by a colon and a space before the error message.

#include <iostream>
using namespace std;

int main() {
  
   // Code tries to open a non existant file "demo.txt"
   FILE * file = fopen("demo.txt", "r");
   // The following string is prepended to the error description.
   perror("Error");
   return(-1);


}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring