The Operating-System Interface

errno and perror/strerror

Imagine asking a clerk to fetch a document, and they come back empty-handed saying just 'no.' That is not very useful - you want to know why: was the document missing, were you not allowed to see it, or was the cabinet locked? Many C functions report failure with a bare 'no' (often a return of minus one), and the 'why' is left in a separate place you can look up afterward. That place is the errno variable.

Mechanically, errno is a special integer the C standard library exposes (it behaves like a global variable, though it is actually per-thread so threads do not clobber each other's error codes). When a system-call wrapper or library function fails, it returns a sentinel value to signal failure - commonly minus one, or NULL for pointer-returning functions - and stores a numeric error code in errno describing the specific reason. Each code has a name, such as ENOENT (no such file or directory), EACCES (permission denied), or EINTR (interrupted). To turn the number into readable text, the standard library offers strerror(), which returns a human-readable string for an error code, and perror(), which prints your message followed by the text for the current errno to standard error. The correct pattern is to check the return value first, and only then read errno - because a successful call does not reset errno to zero.

Why it matters: this is C's primary way of explaining why an operation failed, and using it correctly is the difference between 'it crashed' and 'open failed: No such file or directory.' The crucial discipline is order: errno is only meaningful immediately after a call that signaled failure. Reading errno without first checking that the call actually failed is a classic bug, because functions are not required to clear errno on success, so you might read a stale code left by some earlier call.

FILE *f = fopen("missing.txt", "r"); if (f == NULL) perror("fopen"); - this prints something like: fopen: No such file or directory. perror combined your label 'fopen' with strerror's text for the ENOENT code now sitting in errno.

Check the return first, then turn the errno code into a readable message.

errno is only valid right after a call that reported failure. A successful call is not guaranteed to leave errno as zero, so never test errno on its own to decide whether something failed - test the return value, and read errno only to learn why.

Also called
error numbererrno variable錯誤碼變數錯誤編號