C++ strerror()

The strerror() function in C++ returns the textual description of the system error code.

strerror() prototype

char* strerror( int errnum );

The strerror() takes an argument: errnum which is an integer value that represents the error code. This function converts the error code to a suitable string that describes the error.

The description returned by strerror() is identical to that of perror(). The returned string must not be modified by the program. But it may be overwritten by a subsequent call to the strerror().

It is defined in <cstring> header file.

strerror() Parameters

errnum: An integer value representing the error code.

strerror() Return value

The strerror() function returns a pointer to a null terminated string that consists of the description of the error corresponding to errnum.

Example: How strerror() function works

#include <cstring>
#include <cmath>
#include <cstdio>
#include <cerrno>
#include <iostream>

using namespace std;

int main()
{
    float log_neg = log(-2.5);
    cout << "Log of negative number : " << strerror(errno) << endl;

    /* example.txt does not exist */
    FILE * fp = fopen("example.txt","r");
    if (fp == NULL)
        cout << "Error opening file : " << strerror(errno) << endl;

    return 0;
}

When you run the program, the output will be:

Log of negative number : Numerical argument out of domain
Error opening file : No such file or directory