C++ Standard Library C++ STL Library

C++ <cstring> - strerror() Function



The C++ <cstring> strerror() function interprets the error code errnum and returns a pointer to a null-terminated byte string (C-String) describing the error errnum. The returned message is identical to the description that would be printed by perror().

The returned pointer points to a statically allocated string, which shall not be modified by the program. Further calls to this function may overwrite its content. strerror() is not required to be thread-safe. Implementations may be returning different pointers to static read-only string literals or may be returning the same pointer over and over, pointing at a static buffer in which strerror() places the string.

The error strings produced by strerror() may be specific to each system and library implementation.

Syntax

char* strerror( int errnum );

Parameters

errnum Specify the integral value referring to a error code.

Return Value

Returns a pointer to a null-terminated byte string (C-String) describing error errnum.

Example 1:

The example below shows the usage of strerror() function.

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

using namespace std;

int main(){
  double result = log(0.0);
  cout<<result<<"\n";

  if (errno == ERANGE) {
    cout<<"Value of errno: "<<errno<<"\n";
    cout<<"log(0.0) failed: "<<strerror(errno)<<"\n";
  }
}

The output of the above code will be:

-inf
Value of errno: 34
log(0.0) failed: Numerical result out of range

Example 2:

The example below the strerror() function is used to describe an error when the input argument is out of domain of a mathematical function.

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

using namespace std;

int main(){
  double result = sqrt(-1.0);
  cout<<result<<"\n";

  if (errno == EDOM) {
    cout<<"Value of errno: "<<errno<<"\n";
    cout<<"sqrt(-1.0) failed: "<<strerror(errno)<<"\n";
  }
}

The output of the above code will be:

-nan
Value of errno: 33
sqrt(-1.0) failed: Numerical argument out of domain

Example 3:

Consider one more example where this function is used to describe an error when tried to open a file which does not exist.

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

int main(){
  FILE * pFile;
  pFile = fopen ("wrongfile.txt", "r");
  
  if (pFile == NULL){
    fprintf(stderr, "Value of errno: %d\n", errno);
    perror("Error printed by perror");
    fprintf(stderr, "Error opening file: %s\n", strerror(errno));
  } else {
    fclose (pFile);
  }
}

The output of the above code will be:

Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

❮ C++ <cstring> Library