This guide will discuss the perror function in C, how it works, and how we can use it.

The perror function prints error messages to the stderr stream based on the error state in the errno.

Basic Usage

The syntax for the perror function is:

The perror function accepts one parameter as a pointer to a null-terminated string which contains a descriptive message about the error.

HINT: The errno refers to a  system variable that stores an error code describing an error condition produced by a call to a library function.

REFERENCE: The Linux Manual:

The header file defines the integer variable errno set by system calls and some library functions in the event of an error to indicate what went wrong.

Return Value

The perror function has a void return type, an error message formed by combining the following—in order.

  • The value of the string pointer passed to the function (str).
  • A colon (:)
  • A complete error message describing the error code in errno.
  • A new line character n

Perror Example

We can illustrate the working of the perror by simply opening a non-existent file. The example code for that is:

#include

#include

int main() {


    FILE *fileptr;


    fileptr = fopen(“nothere.txt”, “r”);


    if (fileptr == NULL) {


        perror(“[-]”);


    }


    fclose(fileptr);


    return 0;

}

Once we run the above code, we should get the following example output:

[]: No such file or directory

Bonus

You can download the PDF below to know the error numbers and their meanings.

https://tinyurl.com/errorcodes-meaning

Conclusion

This quick tutorial discussed how to use the perror function to get descriptive error messages encountered in the program.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png61265909211cd.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list