Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using errno for Error Reporting | Handling Runtime and System Errors
C Defensive Programming and Error Handling

bookUsing errno for Error Reporting

When you work with C programs that interact with the system or perform input/output operations, you may encounter situations where a function fails. The C standard library uses a global variable called errno to provide more information about such errors. The errno variable is set by library functions when an error occurs, allowing you to determine the specific cause of the failure. For instance, if you try to open a file that does not exist using fopen, the function returns NULL and sets errno to a value that indicates the reason for the error. You can then use the strerror function to convert the errno value into a human-readable error message, which is very useful for debugging and reporting errors to users.

main.c

main.c

copy
123456789101112
#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; }
question mark

What is the purpose of errno in C?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 12.5

bookUsing errno for Error Reporting

Swipe to show menu

When you work with C programs that interact with the system or perform input/output operations, you may encounter situations where a function fails. The C standard library uses a global variable called errno to provide more information about such errors. The errno variable is set by library functions when an error occurs, allowing you to determine the specific cause of the failure. For instance, if you try to open a file that does not exist using fopen, the function returns NULL and sets errno to a value that indicates the reason for the error. You can then use the strerror function to convert the errno value into a human-readable error message, which is very useful for debugging and reporting errors to users.

main.c

main.c

copy
123456789101112
#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; }
question mark

What is the purpose of errno in C?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 3
some-alt