File Handling

Article · 3:00

FILE pointers, text against binary, and moving around inside a file.

fopen returns a FILE * - an opaque handle onto a buffered stream - or NULL if it failed, which must be checked every time. The mode string decides what you may do and what happens to what is already there: "r" reads and fails if the file is absent; "w" truncates an existing file to zero immediately, which is the mode that destroys data by accident; "a" appends; and adding + allows both reading and writing.

Adding b selects binary mode, and the distinction is real on Windows, where text mode translates \n to \r\n on the way out and back on the way in. On Unix the two are identical. Reading a binary file in text mode on Windows corrupts it silently, so always write "rb" and "wb" for anything that is not text.

For text, fprintf and fscanf mirror their console versions, and fgets is the safe way to read a line. For binary, fread and fwrite move raw bytes and return the number of items transferred, not bytes - checking that count is how you detect a short read.

Random access uses fseek to move, ftell to ask where you are, and rewind to go back to the start. That is what makes a fixed-size record file into something you can index: record n begins at n * sizeof(record).

Close what you open. A FILE * holds a buffer, and data written but not flushed is lost if the program exits without fclose.

#include <stdio.h>
#include <string.h>

typedef struct { int id; char name[32]; double balance; } Record;

int main(void)
{
    /* "w" TRUNCATES an existing file to zero bytes, immediately. */
    FILE *out = fopen("people.txt", "w");
    if (!out) { perror("people.txt"); return 1; }
    fprintf(out, "%d,%s,%.2f\n", 1, "Ada", 120.50);
    fclose(out);                       /* buffered: unflushed data is lost */

    /* Reading a line safely. fgets takes a size and cannot overflow. */
    FILE *in = fopen("people.txt", "r");
    if (!in) { perror("people.txt"); return 1; }
    char line[128];
    while (fgets(line, sizeof line, in)) {
        line[strcspn(line, "\n")] = '\0';
        printf("read: %s\n", line);
    }
    fclose(in);

    /* Binary. The "b" matters on Windows, where text mode rewrites
       newlines and quietly corrupts a binary file. */
    Record records[3] = {
        {1, "Ada",   120.50},
        {2, "Grace",  98.25},
        {3, "Alan",  310.00},
    };

    FILE *bin = fopen("people.dat", "wb");
    if (!bin) return 1;
    /* fwrite returns the number of ITEMS written, not bytes. */
    if (fwrite(records, sizeof *records, 3, bin) != 3) {
        fprintf(stderr, "short write\n");
    }
    fclose(bin);

    /* Random access: record n starts at n * sizeof(Record). */
    bin = fopen("people.dat", "rb");
    if (!bin) return 1;
    Record one;
    fseek(bin, 1 * (long) sizeof one, SEEK_SET);   /* jump to record 1 */
    if (fread(&one, sizeof one, 1, bin) == 1)
        printf("record 1: %d %s %.2f\n", one.id, one.name, one.balance);

    printf("now at byte %ld\n", ftell(bin));
    rewind(bin);
    fclose(bin);
    return 0;
}