Copy a file in C: solved exercise

Copy a file in C: solved exercise

If you are looking for copy a file in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Create a source file, copy it into a destination file, and print the copied content.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>

int main(void) {
    FILE *src = fopen("origen.txt", "w");
    if (!src) {
        return 1;
    }
    fputs("linea1\nlinea2\n", src);
    fclose(src);

    src = fopen("origen.txt", "r");
    FILE *dst = fopen("destino.txt", "w");
    if (!src || !dst) {
        return 1;
    }

    int c;
    while ((c = fgetc(src)) != EOF) {
        fputc(c, dst);
    }
    fclose(src);
    fclose(dst);

    dst = fopen("destino.txt", "r");
    if (!dst) {
        return 1;
    }
    while ((c = fgetc(dst)) != EOF) {
        putchar(c);
    }
    fclose(dst);
    return 0;
}

Expected output

1
2
linea1
linea2

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

This pattern is common in CLI tools, simple persistence, and record processing.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.