Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 135 ยท File Input and Output

Error Handling

Handle errors the C way - check return values, read errno, report problems with perror and strerror, clean up with goto, and design functions that report failure clearly.

C has no exceptions. When something goes wrong (a file is missing, memory runs out, a number doesn't parse), the function that failed tells you so through its return value, and often stores a reason code in a global variable called errno. Nothing stops your program if you ignore those signals: it just keeps running with a NULL pointer or a garbage value until it crashes somewhere far away from the real problem.

Good C programs therefore follow one habit relentlessly: check every call that can fail, right after you make it, and decide what to do. This lesson shows the standard tools for that (return values, errno, perror, strerror, exit codes) and the patterns professionals use to clean up and report errors without drowning the code in repetition.

How standard functions report failure

There's no single convention in the standard library, so you need to know what each function returns on failure. The common cases:

Function Failure value Sets errno?
fopen, malloc, calloc, realloc NULL fopen yes; malloc family on POSIX systems
fclose, fflush, fputs, remove, rename EOF or nonzero yes on POSIX systems
fgets NULL (also at end of file) on read errors
fread, fwrite fewer items than requested on errors
scanf, sscanf, fscanf fewer conversions than expected, or EOF sometimes
strtol, strtod no characters used, or a clamped value ERANGE on overflow
sqrt, log, pow NaN or infinity EDOM/ERANGE (if math_errhandling says so)

The C standard itself promises errno for only a few functions (such as strtol, the math functions and fgetpos); POSIX systems such as Linux and macOS set it for nearly all of them. Treat the return value as the truth about success, and errno as the explanation.

errno, perror and strerror

errno lives in <errno.h>. It's a modifiable int (in reality a macro, so each thread gets its own) that holds the code of the last error. Standard codes include ENOENT (no such file or directory), EACCES (permission denied), ENOMEM (out of memory), EINVAL (invalid argument), ERANGE (result out of range) and EDOM (math argument out of domain).

Two functions turn a code into a readable message:

  • perror("prefix") (in <stdio.h>) prints prefix: message and a newline to stderr, using the current errno.
  • strerror(code) (in <string.h>) returns the message as a string, so you can put it into your own output.
C Reporting why fopen failed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output names the real causes: No such file or directory (errno 2) for the missing file and the missing folder, and Read-only file system for /etc, because our sandbox mounts it read-only. On your own computer the /etc line would more likely say Permission denied. The last fopen reports through perror, which writes no-such-file.txt: No such file or directory to stderr, and the program exits with status 1 (EXIT_FAILURE). The exact message texts come from the C library, so they can differ slightly between Linux, macOS and Windows; the codes like ENOENT are what you compare against in code.

Three rules make errno reliable:

  1. Only look at errno after a call has reported failure. Successful calls are allowed to change errno, so a nonzero value on its own proves nothing.
  2. Save it immediately. printf or any other library call may overwrite it before you use it. Copy it into a local variable first, as try_open does.
  3. Set errno = 0 before calls whose return value can't signal failure on its own, such as strtol (where LONG_MAX is both a valid result and the overflow result) or the math functions.

Tip: Put the thing that failed into the message: the file name, the line number, the value you tried to parse. config.ini: No such file or directory is useful; Error! is not.

errno with numbers and math

Here is the third rule in action. strtol returns LONG_MAX both for the input "9223372036854775807" (a valid value) and for an overflowing input, and only errno tells them apart. The math functions report domain errors the same way when math_errhandling & MATH_ERRNO is set, which it is with glibc:

C errno after strtol and sqrt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

9223372036854775807 is exactly LONG_MAX on our 64-bit server and parses fine, while one digit more sets ERANGE with the message Numerical result out of range. sqrt(-1.0) returns NaN (printed as -nan by glibc) and sets EDOM. Converting Strings and Numbers covers strtol in depth, and The Math Library shows how to check math results without errno.

Exit codes: telling the caller

When main returns, its value becomes the program's exit status. By convention, 0 means success and anything else means failure. <stdlib.h> defines EXIT_SUCCESS (0) and EXIT_FAILURE (1 on most systems) for portability, and exit(status) ends the program from any function with the same effect as returning from main. Shell scripts, build tools and CI systems all look at this status, so a program that prints an error but still returns 0 is lying to them.

Error messages go to stderr, never stdout. When someone runs ./report > out.txt, normal output lands in the file while errors still appear on the screen. Useful stdlib.h Functions covers exit and atexit in more detail.

Cleaning up with goto

The hard part of error handling in C is cleanup. A function that opens two files and allocates a buffer has many ways to fail, and each exit path must release exactly what was acquired so far. Repeating the cleanup at every return is error-prone. The idiom used throughout the Linux kernel, SQLite and countless other projects is a single cleanup section at the end of the function, reached with goto:

C Copying a file with goto cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Every resource starts as NULL, so the cleanup block can release whatever was acquired and skip the rest. There's exactly one return, result stays -1 unless the function reaches the end, and adding a new resource means adding one line to the cleanup block. Notice that closing out can fail too (buffered data is written there), so its result feeds into result. break, continue and goto explains why this is the one widely accepted use of goto.

Designing your own error reporting

When you write functions that can fail, pick a clear convention and use it consistently. The common choices:

  • Return 0 for success and -1 (or a negative code) for failure, like POSIX. Simple, but the caller learns little about why.
  • Return a pointer, NULL on failure, like fopen and malloc. Natural for functions that create something.
  • Return an error code enum and deliver the real result through an out-parameter. This scales best, because every failure has a name and a message, and the return value is free for errors.
C An error enum with messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The switch in parse_error_message has no default, on purpose: if you add a new enum value and forget its message, -Wall warns about the unhandled case. The caller only touches port when the result is PARSE_OK, so it never reads an uninitialized value.

A few more guidelines that experienced C programmers follow:

  • Decide who reports. Low-level functions return codes; the top level (often main) decides how to show them. Printing inside a library function makes it impossible to reuse quietly.
  • Don't leave half-done results. If a function fails, leave out-parameters untouched or in a documented state, and free anything it allocated.
  • Fail fast on programmer errors. A NULL passed where it's never allowed is a bug, not a runtime condition; assert catches it during development.
  • Mark results that must be checked. C23's [[nodiscard]] attribute (and GCC's older __attribute__((warn_unused_result))) makes the compiler warn when a caller ignores the return value:
C
[[nodiscard]] int save_settings(const char *path);   /* C23 */

save_settings("app.cfg");
/* warning: ignoring return value of 'save_settings', declared with attribute 'nodiscard' */

Note: Some standard functions return a pointer to a static buffer or keep hidden state (strerror, strtok, localtime), so they aren't safe to call from several threads at once. POSIX offers strerror_r, and C11's optional Annex K offers strerror_s. In single-threaded programs, plain strerror is fine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A call to fopen succeeded, but errno is 2 afterwards. What does that mean?

    errno is only meaningful right after a function has signaled failure through its return value. Library functions may set it internally even when they succeed.
  2. 2. Why does code set errno = 0 before calling strtol?

    strtol has no failure return value for overflow; it clamps to LONG_MAX or LONG_MIN and sets errno to ERANGE. Clearing errno first makes that check reliable.
  3. 3. Where does perror write its message?

    perror prints the prefix, a colon, a space and strerror(errno) to stderr. Use strerror when you need the message as a string.
  4. 4. In the goto cleanup pattern, why is every resource initialized to NULL?

    Jumping to cleanup from any point is safe when unacquired resources are NULL. free(NULL) does nothing, and the if checks skip files that were never opened.
  5. 5. A program prints "error: cannot open config" but returns 0 from main. What's the problem?

    The exit status is how a program reports success to its caller. Failures should exit with a nonzero status such as EXIT_FAILURE.

Summary

  • C functions report failure through their return value (NULL, EOF, -1, a short count); check it right after every call that can fail.
  • errno (from <errno.h>) explains why. Read it only after a reported failure, save it immediately, and set it to 0 before calls like strtol and math functions whose return value can't signal errors.
  • perror("context") prints the message to stderr; strerror(code) returns it as a string. Include the file name or value in every message.
  • Return EXIT_FAILURE (or call exit) when the program fails, and print errors to stderr.
  • Use the goto cleanup pattern for functions that acquire several resources: initialize everything to NULL, jump to one cleanup block, return one result.
  • For your own functions, choose a consistent convention; an error enum with a message function plus out-parameters scales well. C23 [[nodiscard]] warns callers who ignore results.

Next: Low-Level I/O with System Calls.