C Programming

strerror 2 C Function

System errors do occur. As soon as your program tries to reach the operating system, something goes wrong. If this occurs, the function returns -1, and your code must rely on our trusty errno to figure out what went wrong and perhaps emit an instructive error message. The C library calls char *strerror(int errnum), which produces a reference to a string comprising of the error message, and searches an internal array for the error number errnum. Depending on the compiler and platform used for development, strerror generates error strings, and converts a string of error messages to the error number in errnum.

Errno values with proper errnums are required. A locale-specific error message string is not produced by this function. The library contains variables and functions intended to make it simple for your program to provide detailed error message failure on the part of a library call in the usual format. You can get the default error message for a certain error code using the strerror methods, and you can quickly get the name of the program that made the error using the variable program invocation short name. Let’s investigate the C language’s strerror function in greater detail.

Syntax of the strerror Function in C Language

We use the following syntax of the function strerror() in the C language. The string that explains the mistake is obtained using this strerror syntax.

char *strerror(int  errnum );

We have only one argument which the strerror function takes. The argument is errnum: a specific error for which you’d like to receive the error message. If the runtime error is unknown, the strerror() function provides an unknown error message. Otherwise, it gives the relevant error description string.

The value of errno remains unchanged if the operation is successful; if not, it is changed to a nonzero value. Furthermore, the strerror function generates two errors, EINVAL and ERANGE. If the errnum’s value is an invalid error number, the EINVAL error is thrown. When the error description string could not be stored on the provided storage, the error generated is ERANGE.

Example 1

Here, we have demonstrated the utilization of the strerror function. We will utilize this in our C program to generate the error upon the execution. Let’s discuss the implementation for this strerror function. We are required to include some library header files of C, which are required for this code implementation.

First, we have inserted the stdio.h header file. We must include the header file stdio.h to add the input/output-related methods in our program. Then, the string.h is added after the stdio.h header file. The header for the C standard library is called string.h. However, the name is a little deceptive because it comprises macro declarations, constants, and declarations of methods and types, These are used for handling multiple memory handling functions in addition to managing strings. As this is the code of the strerror function to access this function, we need to import an error.h file for this function.

The C programming language’s standard library contains the header file errno.h. It defines macros with the errno symbol to report and retrieve error circumstances (abbreviation for “error number”). Certain library functions that detect errors save a value such that the error number is in the errno variable. The only values that library functions store are ones greater than zero.

Regardless of whether they notice mistakes, any library function may change the value that is saved before returning. The majority of functions report errors by returning a specific value, generally NULL for methods that return pointers and -1 for methods that return integers. The caller of a few functions must set errno to 0 and examine it afterward to check if an error was found.

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

int main () {
   FILE *fp;

   fp = fopen("file.txt","r");
   if( fp == NULL ) {
      printf("Error: %s\n", strerror(errno));
   }
   
   return(0);
}

After including the header file, we have the main function declaration. Within the main function section, we have created the file pointer “fp” with the FILE object. The file is assigned a file name with the read mode inside the fopen function if the condition is applied to the fp pointer variable. If the fp is found NULL, then the printf statement is executed which has the strerror function. The strerror function takes the errno as an argument and returns this in a string form.

Because we are attempting to open a file that isn’t present, let’s compile and run the program mentioned above, which will result in the following outcome:

Example 2

As the previous code generates the error string itself when this occurs. We can also define the string error by ourselves. We have to define the error string first with the errno.

int main(int argc, char *argv[])
{
    FILE *fout;
    int last_error = 0;
    if ((fout = fopen(argv[1], "w")) == NULL) {
        last_error = errno;
         errno = 0;
    }
    if (last_error) {
        fprintf(stderr, "fopen: Could not open %s for writing: %s",
                argv[1], strerror(last_error));
        fputs("continue…\n", stderr);
    }
    return EXIT_SUCCESS;
}

We have inserted several header files for this example code and each one has its functionality and purpose. Then, we have established the main function. The fout is created as the pointer variable and the last_error is also declared as the variable, which is assigned with the value 0. The nested if expressions are utilized here. If the last_errror condition is matched with the errorno, then we can specify the last_error in the strerror function.

The string error defined by the user is produced when the previous code is executed, as shown below:

Conclusion

The guide’s main purpose is to educate you about the strerror in C language. By utilizing the error.h header file in the code, we can easily access the strerror function. The syntax is very easy to understand. Here, we discussed two examples which will explain the usage of the strerror in C language. We can also create or define the error into the string error which we want to display.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.