Error Handling with errno and perror in C

 Error Handling with errno and perror in C


The errno variable is set by system calls and library functions to indicate errors. The perror function can be used to print 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;

    }


    // Code to work with the file


    fclose(file);


    return 0;

}

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...