typestar

Copying a file in blocks in C

A fixed buffer, read until short, write exactly what was read.

#include <stdio.h>

int copy_file(const char *from, const char *to) {
    FILE *in = fopen(from, "rb");
    if (in == NULL) {
        return 0;
    }
    FILE *out = fopen(to, "wb");
    if (out == NULL) {
        fclose(in);
        return 0;
    }

    char buffer[4096];
    size_t n;
    int ok = 1;
    while ((n = fread(buffer, 1, sizeof buffer, in)) > 0) {
        if (fwrite(buffer, 1, n, out) != n) {
            ok = 0;
            break;
        }
    }
    ok = ok && !ferror(in);
    fclose(in);
    return (fclose(out) == 0) && ok;
}

How it works

  1. The buffer size trades memory for system calls.
  2. Write only as many bytes as the read returned.
  3. Both streams are closed on every path out.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
427
Tokens
163
Three-star pace
100 tpm

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

Type this snippet

Step 3 of 4 in Writing & binary, step 7 of 12 in Files & I/O.

← Previous Next →