CFile Handling Basics

File Handling Basics

Every variable, array, and struct you have used so far lives only in memory — the moment the program exits, it is gone. File I/O is how a C program persists data beyond its own execution: writing results to disk so they survive after the process ends, and reading them back later, possibly from an entirely different run of the program (or a different program altogether).

The FILE* Abstraction

The C standard library (<stdio.h>) represents an open file with an opaque type called FILE. You never touch a FILE directly — you always work through a pointer to it, FILE *, which the library hands you when you open a file and which you pass to every subsequent read, write, or close operation.

C
#include <stdio.h>

int main(void)
{
    FILE *fp;   /* a handle to an open file, not the file's data itself */

    fp = fopen("notes.txt", "w");
    if (fp == NULL) {
        printf("Could not open file.\n");
        return 1;
    }

    fprintf(fp, "Persisted to disk.\n");
    fclose(fp);

    return 0;
}

Think of FILE * as a handle or ticket, not the file's actual bytes — it tracks bookkeeping like the current read/write position, internal buffers, and error/EOF state on your behalf.

The General Workflow
  • Open the file with fopen(), specifying a path and a mode (read, write, append, ...)

  • Read or write through the returned FILE *, using functions like fprintf, fscanf, fgets, fread, fwrite, and friends

  • Close the file with fclose() once you are done, releasing the underlying resource and flushing any buffered writes to disk

Every file operation can fail — check it
Opening a file can fail because the path does not exist, a directory has no read permission, the disk is full, or the process has hit its limit of open file handles. Reading and writing can fail too, mid-stream. Production C code checks the return value of `fopen`, and the return values / error state of every subsequent read and write, rather than assuming success. This theme comes up again and again in the following file-handling pages — treat it as the golden rule of file I/O in C.
What's ahead
The next pages walk through opening and closing files properly, text-based reading and writing, binary I/O for raw data, seeking to arbitrary positions within a file, and handling the errors that inevitably come up along the way.