typestar

Writing a formatted report in C

fprintf writes to any stream with the same format language as printf.

#include <stdio.h>

typedef struct {
    const char *lang;
    int tpm;
    double accuracy;
} Row;

int write_report(const char *path, const Row *rows, size_t n) {
    FILE *f = fopen(path, "w");
    if (f == NULL) {
        return 0;
    }
    fprintf(f, "%-10s %6s %9s\n", "lang", "tpm", "accuracy");
    for (size_t i = 0; i < n; i++) {
        fprintf(f, "%-10s %6d %8.1f%%\n", rows[i].lang, rows[i].tpm,
                rows[i].accuracy);
    }
    return fclose(f) == 0;
}

How it works

  1. The only difference from printf is the stream argument.
  2. Column widths in the format string line the output up.
  3. Check the return value when the write really matters.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
407
Tokens
142
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 1 of 4 in Writing & binary, step 5 of 12 in Files & I/O.

← Previous Next →