strerror in C

In this blog post, you will learn what is the strerror in C and how to use the strerror() function in C with the help of programming examples.

 

What is strerror() in C?

The strerror function maps errnum to an error-message string. Typically, the values for errnum come from errno, but strerror can map any value of type int to a message.

 

Syntax of strerror():

The following is the syntax of the strerror function in C.

char *strerror(int errnum);

 

strerror Parameters:

The strerror() function accepts the following parameters:

errnum – integral value referring to an error code

 

strerror() return value:

The strerror function returns a pointer to the string. The contents of the string are locale-specific and must not be modified by the program.

The behavior is undefined if the returned value is used after a subsequent call to the strerror function, or after the thread called the function to obtain the returned value has exited.

 

Note: The strerror_s function can be used instead to avoid data races.

 

Example program to describe how to use strerror in C:

The following program illustrates the working of the strerror() function in the C language.

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main ()
{
    FILE *fptr = fopen("Aticleworld.txt","r");
    if( fptr == NULL )
    {
        printf("Error: %s\n", strerror(errno));
    }

    return(0);
}

Output: Error: No such file or directory

 

Recommended Post: