Codiqo

Learn C · lesson 47 of 60 · about 10 minutes

Capstone: Files and Errors

Save the bill to a file, load it back, and handle a missing file gracefully.

What you'll learn

  • Write a file with fopen and fprintf
  • Read it back with fgets and sscanf
  • Handle fopen failures

A bill that's still there tomorrow

The bill is saved to bill.csv, one cost per line with commas between the parts, by save_bill, which opens the file with "w", writes with fprintf and closes it. load_bill opens it with "r", reads each line with fgets and pulls it apart with %23[^,],%11[^,],%d, and gives back how many costs it loaded, or -1 if the file couldn't be opened. Main first tries a file that doesn't exist and says No saved bill yet., then saves the bill, loads it into a second Bill and prints how many came back and their total.

Files in C

  • FILE *f = fopen("expenses.csv", "w"); opens a file for writing ("r" reads, "a" appends)
  • fopen returns NULL if it fails, for example when the file doesn't exist yet
  • fprintf(f, ...) writes like printf; fgets(line, size, f) reads a line
  • fclose(f) finishes and releases the file

The format is CSV: one expense per line, values separated by commas.

Save and load

#include <stdio.h>

typedef struct {
    char what[24];
    char category[12];
    int pence;
} Expense;

int save(const char *path, const Expense *items, int n) {
    FILE *f = fopen(path, "w");
    if (f == NULL) return 0;
    for (int i = 0; i < n; i++) fprintf(f, "%s,%s,%d\n", items[i].what, items[i].category, items[i].pence);
    fclose(f);
    return 1;
}

int load(const char *path, Expense *items, int max) {
    FILE *f = fopen(path, "r");
    if (f == NULL) return -1;
    char line[80];
    int n = 0;
    while (n < max && fgets(line, sizeof line, f)) {
        Expense *e = &items[n];
        if (sscanf(line, "%23[^,],%11[^,],%d", e->what, e->category, &e->pence) == 3) n++;
    }
    fclose(f);
    return n;
}

int main(void) {
    Expense loaded[10];
    printf("before saving: %d\n", load("expenses.csv", loaded, 10));

    Expense mine[] = {{"Lunch", "food", 650}, {"Bus fare", "travel", 205}};
    save("expenses.csv", mine, 2);

    int n = load("expenses.csv", loaded, 10);
    printf("loaded %d: %s (%s) %d\n", n, loaded[1].what, loaded[1].category, loaded[1].pence);
    return 0;
}

Output

before saving: -1
loaded 2: Bus fare (travel) 205

Tip

%23[^,] means "read up to 23 characters that aren't commas", which lets descriptions contain spaces like "Bus fare".

Errors you can see coming

A missing file is normal the first time the report runs, so it isn't treated as a crash: load_bill returns -1 and main prints a friendly line. A file that can't be written is different, because the bill would be lost, so main prints Could not save the bill. and stops with return 1. Every fopen is checked for NULL before the file is used, and every file that was opened is closed.

A return value that means two things

#include <stdio.h>

int count_lines(const char *path) {
    FILE *f = fopen(path, "r");
    if (f == NULL) {
        return -1;
    }
    char line[80];
    int n = 0;
    while (fgets(line, sizeof line, f) != NULL) {
        n++;
    }
    fclose(f);
    return n;
}

int main(void) {
    int n = count_lines("never-saved.csv");
    if (n == -1) {
        printf("No file yet\n");
    } else {
        printf("%d lines\n", n);
    }
    return 0;
}

Output

No file yet

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.