Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

C Header Files

C Library – errno.h

Posted in C Tutorial
Updated on Oct 06, 2024
By Mari Selvan
👁️ 48 - Views
⏳ 4 mins
💬 1 Comment
C Library - errno.h

Photo Credit to CodeToFun

🙋 Introduction

The errno.h header in C defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong. The errno variable is set to zero at program startup and is never reset by any library function. Therefore, it should be explicitly reset to zero before calling a function if the program needs to check for errors.

💡 Syntax

To use the errno.h library, you need to include it in your program:

Syntax
Copied
Copy To Clipboard
#include <errno.h>

❗ Important Macros and Variables

The errno.h header defines a variable and several macros that represent different error codes. Some common error codes include:

  • EDOM: Domain error, typically used when a function like sqrt receives a negative argument.
  • ERANGE: Range error, typically used when a result is too large to be represented.
  • EINTR: Interrupted function call.
  • EINVAL: Invalid argument.

Syntax for Using errno

  • Declaring errno:

    example.c
    Copied
    Copy To Clipboard
    extern int errno;
  • Checking errno after a function call:

    example.c
    Copied
    Copy To Clipboard
    #include <errno.h>
    #include <stdio.h>
    #include <math.h>
    
    int main() {
        errno = 0;  // Reset errno before function call
        double result = sqrt(-1);
    
        if (errno != 0) {
            perror("Error occurred");
        }
    
        return 0;
    }

📄 Example

Below is a simple example demonstrating how to use the errno variable and perror function to handle errors. This example attempts to open a file that does not exist and checks the errno value if the fopen function fails.

example.c
Copied
Copy To Clipboard
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *file = fopen("nonexistent.txt", "r");

    if (file == NULL) {
        printf("Error opening file: %s\n", strerror(errno));
    } else {
        fclose(file);
    }

    return 0;
}

💻 Output

Output
Error opening file: No such file or directory

🧠 How the Program Works

  • Function Call: The fopen function attempts to open a file named "nonexistent.txt" for reading.
  • Error Handling: If the file does not exist, fopen returns NULL, and errno is set to indicate the error.
  • Printing the Error: The strerror function converts the errno value to a human-readable string, which is printed to the console.

🚧 Common Pitfalls

  1. Not Resetting `errno`: Forgetting to reset errno before a function call can lead to incorrect error handling, as errno may still hold a value from a previous error.
  2. Ignoring `errno`: Not checking errno after a function that sets it can cause missed error conditions and lead to undefined behavior.
  3. Misinterpreting `errno` Values: Misunderstanding the meaning of specific errno values can lead to improper error handling.

✅ Best Practices

  1. Always Reset `errno`: Set errno to zero before a function call if you intend to check it for errors.
  2. Check `errno` Immediately: Check errno immediately after the function call to ensure that no other operations have altered it.
  3. Use `perror` or `strerror`: Utilize perror or strerror to print meaningful error messages instead of just printing the errno value.
  4. Document Error Handling: Clearly document which functions set errno and what the expected error codes are, to ensure proper error handling.

🎉 Conclusion

The errno.h header is an essential tool for error handling in C, allowing programs to detect and respond to errors effectively.

By understanding how to use errno and related macros, programmers can create more robust and reliable code. However, it is crucial to follow best practices and be aware of common pitfalls to avoid potential issues in error handling.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy