AppDividend
Latest Code Tutorials

C++ strerror() Function Example | strerror() in C++

0

C++ strerror() is an inbuilt string handling function that returns the description of the type of system error that occurred in the program. It is defined in <string.h> header file. It takes an integer parameter, which represents the error code. With the help of this function strerror(), we covert the error code in the string, which shows the error in the text format. This strerror() function is often compared with perror(). They both return the identical error description.

C++ strerror()

The strerror() method in C++ returns the textual description of a system error code. The strerror() takes the argument: ernum, which is the integer value that represents an error code. The strerror() method converts the error code to the suitable string that describes the error. The description returned by strerror() function is identical to that of perror(). The program must not modify the returned string. But it may be overwritten by the subsequent call to the strerror().

Syntax

char* strerror( int num );

Parameters

It takes one parameter of integer data type, which represents the error in code format. By using this function, we change the error in textual format.

Return Type

It returns a pointer to a string that consists textual representation of the error code.

Example programs on strerror() function in C++

Example 1: Write a program to show the working of strerror() function.

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

using namespace std;

int main()
{
  float log_neg = log(-9);
  cout << "Log of -9 : " << strerror(errno) << endl;
  return 0;
}

Output

Log of -9:  Domain error

Example 2: Write a program to check if a file exists in the system and if it doesn’t throw a descriptive textual error showing that the file doesn’t exist.

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

using namespace std;

int main()
{
  FILE *f = fopen("k.txt", "r");
  if (f == NULL)
  {
    cout << "File doesn't exist error : " << strerror(errno) << endl;
  }
}

Output

File doesn't exist error:  No such file or directory

See also

C++ strlen()

C++ strstr()

C++ strtok()

C++ strspn()

C++ strpbrk()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.