How to copy a file in C programming

How to copy a file in C:

In this post, we will learn how to copy a file in C. With this program, you will learn how to do basic file operations in C like opening a file in read/write mode, reading contents from a file C and writing text to a file in C.

Actually, we can’t copy a file directly in C. We will open one file, read the file content and write that content to the new file.

For reading the data, we can open the file in read mode and for writing, we need to open it in write mode.

Steps to copy a file in C:

We will follow the following steps to do the copying operation:

  • Open the file in read mode. This is the file to copy.
  • Open the other file in write mode. This is the file to copy data from the above file.
  • Read the content of the first file using a loop. This loop will read character by character and write that to the second file simultaneously.
  • Once complete reading and writing is done, close the files.

C program to copy a file:

Below is the complete C program that copies a text file:

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

int main()
{
    FILE *readFile, *writeFile;
    char readFilePath[100] = "input.txt";
    char writeFilePath[100] = "output.txt";
    char buffer;

    readFile = fopen(readFilePath, "r");

    if (readFile == NULL)
    {
        printf("File opening failed for %s", readFilePath);
        exit(0);
    }

    writeFile = fopen(writeFilePath, "w");
    if (writeFile == NULL)
    {
        printf("File opening failed for %s", writeFilePath);
        exit(0);
    }

    buffer = fgetc(readFile);
    while (buffer != EOF)
    {
        fputc(buffer, writeFile);
        buffer = fgetc(readFile);
    }

    printf("Copying completed");
    fclose(readFile);
    fclose(writeFile);
    return 0;
}

Here,

  • We have created two FILE pointers readFile and writeFile. These variables will hold the pointer to the file after we open them.
  • readFilePath and writeFilePath are paths of the input and output files respectively. In this program, we are reading contents from the input.txt file in the same folder and writing the contents to output.txt file in that folder.
  • We need to use fopen to open a file. The first file is opened in read mode and the second one is opened in write mode. While opening in read mode, if the file doesn’t exists, it throws an error. But in write mode, if it doesn’t exists, it creates that file.
  • buffer is the character where we are storing the reading value temporarily. It will be EOF once the end of the file is reached.
  • The while loop keeps reading the contents from the readFile and it keeps writing to writeFile.

If you run this program, it will create one new file output.txt in the same folder and copy all contents of input.txt to output.txt.

You might also like: