0
0
CHow-ToBeginner · 3 min read

How to Copy a File in C: Simple Example and Syntax

To copy a file in C, open the source file in "rb" mode and the destination file in "wb" mode, then read from the source and write to the destination in a loop until the entire file is copied. Use fopen, fread, fwrite, and fclose functions for this process.
📐

Syntax

To copy a file in C, you typically use these functions:

  • fopen(filename, mode): Opens a file with the given mode (e.g., "rb" for reading binary, "wb" for writing binary).
  • fread(buffer, size, count, file): Reads data from the file into a buffer.
  • fwrite(buffer, size, count, file): Writes data from the buffer to the file.
  • fclose(file): Closes the opened file.

You read chunks of data from the source file and write them to the destination file until the entire file is copied.

c
FILE *source = fopen("source.txt", "rb");
FILE *dest = fopen("dest.txt", "wb");
char buffer[1024];
size_t bytesRead;

while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
    fwrite(buffer, 1, bytesRead, dest);
}

fclose(source);
fclose(dest);
💻

Example

This example copies the contents of input.txt to output.txt. It reads the file in chunks of 1024 bytes and writes them to the new file until done.

c
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *source = fopen("input.txt", "rb");
    if (source == NULL) {
        perror("Error opening source file");
        return 1;
    }

    FILE *dest = fopen("output.txt", "wb");
    if (dest == NULL) {
        perror("Error opening destination file");
        fclose(source);
        return 1;
    }

    char buffer[1024];
    size_t bytesRead;

    while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
        fwrite(buffer, 1, bytesRead, dest);
    }

    fclose(source);
    fclose(dest);

    printf("File copied successfully.\n");
    return 0;
}
Output
File copied successfully.
⚠️

Common Pitfalls

  • Not checking if fopen returns NULL, which means the file could not be opened.
  • Using text mode ("r" or "w") instead of binary mode ("rb" or "wb") when copying binary files, which can corrupt the data.
  • Not handling partial reads or writes properly, which can cause incomplete copying.
  • Forgetting to close files with fclose, which can lead to resource leaks.
c
// Wrong way (no error check, text mode):
FILE *src = fopen("file.bin", "r");
FILE *dst = fopen("copy.bin", "w");
char buf[512];
while (fread(buf, 1, sizeof(buf), src) > 0) {
    fwrite(buf, 1, sizeof(buf), dst); // wrong: always writes full buffer
}
fclose(src);
fclose(dst);

// Right way (with error check and binary mode):
FILE *src = fopen("file.bin", "rb");
if (!src) { perror("Open source"); exit(1); }
FILE *dst = fopen("copy.bin", "wb");
if (!dst) { perror("Open dest"); fclose(src); exit(1); }
size_t n;
char buf[512];
while ((n = fread(buf, 1, sizeof(buf), src)) > 0) {
    fwrite(buf, 1, n, dst);
}
fclose(src);
fclose(dst);
📊

Quick Reference

Remember these key points when copying files in C:

  • Always open files in binary mode for copying.
  • Check if fopen returns NULL before proceeding.
  • Use a buffer to read and write chunks of data.
  • Handle partial reads/writes by using the actual number of bytes read.
  • Close all files after operations to free resources.

Key Takeaways

Open source and destination files in binary mode using fopen with "rb" and "wb".
Use fread and fwrite in a loop to copy data in chunks until the entire file is copied.
Always check if fopen returns NULL to handle file open errors gracefully.
Close all opened files with fclose to avoid resource leaks.
Handle partial reads and writes by using the actual number of bytes processed.