Library contents

C fread and fwrite

Copy a file to an independent destination before editing it.

A simple example

fread and fwrite

  1. Start with Source file containing A
  2. Do this Copy to a second file
  3. Result Both contain A
A copy keeps the original and creates another file with the same contents.

Syntax

C syntax
fwrite(buffer, 1, count, destination)
Run these examples in C

Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Keep a separate copy of a receipt

A cashier gives a customer an annotated receipt and keeps the original for the daily ledger. Copy the saved receipt, add a note to the customer copy, and check what remains in the original.

From the programint ok = 0
Resultpaid
lesson.c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    FILE *original = tmpfile(), *copy = tmpfile();
    int ok = 0;
    if (original && copy && fputs("paid", original) >= 0 && fseek(original, 0, SEEK_SET) == 0) {
        char data[64] = {0};
        size_t count = fread(data, 1, sizeof data - 1, original);
        ok = !ferror(original) && count == 4 && fwrite(data, 1, count, copy) == count;
        if (ok && fseek(copy, 0, SEEK_SET) == 0 && fputs("collected", copy) >= 0 &&
            fseek(original, 0, SEEK_SET) == 0 && fgets(data, sizeof data, original)) puts(data);
        else ok = 0;
    }
    if (original) fclose(original);
    if (copy) fclose(copy);
    return ok ? 0 : 1;
}
Output
paid

The original still contains only the payment status after the destination changes.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?

GivenFile contents “clay”
Worked resultclay

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Make a second copy for the afternoon shift. Which text does the new file contain?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

These C examples use POSIX file APIs on macOS or Linux. Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.

Documentation for fread and fwrite