strerror() function in C++

In this guide, you will learn what is strerror() function is in C++ programming and how to use it with an example.

1. strerror() Function Overview

The strerror() function is a part of the <cstring> library in C++. It returns a pointer to a string that describes the error code passed in the argument. This function is useful for translating error numbers (like those returned by the errno variable) into a human-readable string.

Signature:

const char* strerror(int errnum);

Parameters:

- errnum: The error number, typically obtained from the errno variable, for which a description is required.

2. Source Code Example

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

int main() {
    // Intentionally making a mistake to cause an error
    FILE *file = fopen("nonexistent.txt", "r");

    if (!file) {
        std::cout << "Error: " << strerror(errno) << std::endl;
    }

    return 0;
}

Output:

Error: No such file or directory

3. Explanation

1. We've included the <iostream> header for standard input/output operations, <cstring> for the strerror() function, and <cerrno> to get access to the errno variable.

2. We attempt to open a file that does not exist. This action will cause an error and set the errno variable.

3. When the file doesn't open successfully, we use the strerror() function to get a human-readable description of the error using the error number stored in errno.


Comments