C fread and fwrite
Copy a file to an independent destination before editing it.
A simple example
fread and fwrite
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
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
./lessonKeep 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.
#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;
}
paid
The original still contains only the payment status after the destination changes.
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?
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?
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.