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