Skip to content

Chapter 5 of 7

File I/O and Program Termination

File operations in C begin with fopen, which takes a filename and a mode string. The standard text modes are r, w, and a, while binary variants rb, wb, and so on are required for images, archives, or structured records because text mode on Windows translates newlines to and from the carriage-return-plus-linefeed sequence. Always check that the returned FILE pointer is not NULL before proceeding. For reading, fgetc reads one character at a time, fgets reads a line into a buffer with a size limit, fscanf does formatted input, and fread reads binary records; their writing counterparts are fputc, fputs, fprintf, and fwrite. The pair fprintf and fscanf mirror printf and scanf but take a FILE pointer as their first argument, so fprintf(stdout, ...) behaves like printf and fprintf(stderr, ...) writes to the usually unbuffered standard error stream. The return value of printf indicates the number of characters written, which is worth checking for output errors.

Always close files with fclose to flush buffered output and release the underlying file descriptor; failing to do so risks data loss from unflushed buffers and resource leaks because file descriptors are limited. Use fseek with SEEK_SET, SEEK_CUR, or SEEK_END to reposition the file pointer, ftell to query the current offset, rewind as shorthand for fseek to the start, and fflush to push buffered output even without a newline; fflush(NULL) flushes every output stream. The feof function only returns true after a read has attempted to pass the end of the file, so the idiomatic loop reads first and then checks the return value rather than predicting EOF ahead of time.

Programs terminate in several ways. Returning a value from main causes the runtime to call exit, which runs atexit handlers in LIFO order, flushes and closes stdio buffers, and returns the status to the host; exit(EXIT_SUCCESS) and exit(EXIT_FAILURE) are portable. abort terminates abnormally by raising SIGABRT without flushing buffers or running handlers, often producing a core dump. assert(expr) from <assert.h> checks an internal invariant at runtime, printing file and line and calling abort if false; defining NDEBUG before including the header disables all asserts at compile time, so asserts are for internal invariants rather than validating external input. The errno variable, set by many library functions on failure, can be displayed with perror("prefix") or strerror(errno) and should be set to zero before a call and checked afterward. Beyond these, <stdlib.h> offers qsort for in-place sorting via a comparator, bsearch for binary search on a sorted array, rand and srand for pseudo-random numbers (note that rand() % N is biased and prefers scaling), and getopt for parsing command-line options with short flags and optarg for option arguments. POSIX clock_gettime measures elapsed time at nanosecond resolution, signal and sigaction install handlers for events like SIGINT (though only async-signal-safe functions may be called inside a handler), and setjmp with longjmp provides non-local jumps out of deeply nested calls.

All chapters
  1. 1Pointers and Dynamic Memory
  2. 2Data Types, Variables, and User-Defined Aggregates
  3. 3Arrays, Strings, and Memory Operations
  4. 4Functions and Control Flow
  5. 5File I/O and Program Termination
  6. 6The Preprocessor and Macros
  7. 7Compilation, Linking, and Program Structure

Drill it

Reading is not remembering. These come from the C Programming deck:

Q

What is a pointer in C?

A pointer is a variable that stores the memory address of another variable.Declared using the * operator: int *ptr;The address-of operator &amp; retrieves a var...

Q

How do you dereference a pointer?

Dereferencing means accessing the value stored at the address a pointer holds.Use the * operator: int val = *ptr;This retrieves the value at the memory location...

Q

What is a NULL pointer?

A NULL pointer is a pointer that does not point to any valid memory location.Assigned with: int *ptr = NULL;Always check for NULL before dereferencing to avoid...

Q

What does malloc() do in C?

malloc() allocates a block of memory on the heap and returns a pointer to it.Syntax: int *p = (int *)malloc(n * sizeof(int));Returns NULL if allocation fails. M...