C++ perror()

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
72282
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
72282
5
Start Learning
Topics Covered

Overview

The function perror is used to display a string (i.e., description of the error) before the error message stored in errno and displayed in stderr (standard error output stream). The error code stored in errno describes the condition of the error that occurs in the code after the execution.

The errno is a system variable where all the error codes are saved and the condition of the error is produced when the library gets called.

Syntax of C++ perror()

The syntax of the function perror: -

Let us understand the syntax using the following image.

Syntax of C++ perror()

Parameters of C++ perror()

The function perror only takes one parameter i.e., str which is a pointer that points to the string added before the description of the error.

Return Value of C++ perror()

The return type of the function perror is void therefore there is no return value of perror().

Exceptions of C++ perror()

There are no exceptions present for the function perror().

How Does C++ perror() Work?

The function perror has a return type of void and takes a string (pointer to a string) as an input. It displays the string entered in the function perror followed by a colon and a space and then the error message that is already saved in the system variable errno and displayed on stderr (i.e., standard error output stream).

Example

Let us look at an example where we will try to access a file that does not exist which will raise an error that is No such file or directory that is already saved in errno. Here, we will add a custom message before the error is printed as given in the following code. After we run the program, the message that we entered in the function gets printed followed by a colon(:) and a space.

Output

After the program is executed, the string entered i.e., "The file does not exist" in the perror() function is displayed before the error description followed by a colon and a space.

Conclusion

  • The perror function is used to display the error message before the error description stored in the system variable errno to stderr (standard error output stream).
  • The perror function takes only one parameter that is a pointer to a string that is added before the error description.
  • There is no return type to the perror function because its return type is void.
  • The string entered in the perror function gets displayed followed by a colon and a space before the error message (the error message is that already saved in system variable errno)