How to use perror() in C++
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
errnovariable is of typeint– 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.
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
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);}
Free Resources