C Programming

Perror Function in C

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:

void perror(const char* str);

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 <errno.h> 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 <stdio.h>
#include <errno.h>

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

Conclusion

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

About the author

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