Error Handling with errno and perror in C

 Error Handling with errno and perror in C


C provides mechanisms for handling errors using the errno variable and the perror function. errno is a global variable that indicates the type of error that occurred, and perror prints a descriptive error message based on the value of errno.


#include <stdio.h>

#include <stdlib.h>

#include <errno.h>


int main() {

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


    if (file == NULL) {

        perror("Error");

        printf("Error code: %d\n", errno);

        return 1;

    }


    fclose(file);


    return 0;

}

In this example, the program attempts to open a nonexistent file. If the file cannot be opened, an error message is printed using perror, and the value of errno is displayed.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...