typestar

Opening and closing files in C

fopen returns NULL on failure, and every successful open needs a matching close.

#include <stdio.h>

int write_greeting(const char *path) {
    FILE *f = fopen(path, "w");
    if (f == NULL) {
        return 0;
    }
    fprintf(f, "hello from C\n");
    return fclose(f) == 0;
}

long file_size(const char *path) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    fclose(f);
    return size;
}

How it works

  1. The mode string picks read, write, append and text or binary.
  2. Mode w truncates an existing file, while a appends to it.
  3. Checking for NULL is not optional.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
336
Tokens
117
Three-star pace
95 tpm

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

Type this snippet

Step 1 of 4 in Opening & reading, step 1 of 12 in Files & I/O.

Next →