C

C Program to Copy the Contents of One File to Another

In this tutorial, we are going to see how to write a program to copy the contents of one file to another in C. We must first specify the file to copy, then the target file. We will open the file we want to copy in “read” mode and the target file in “write” mode, as shown below in the program.
 

Write a Program to Copy the Contents of One File to Another in C
#include <stdio.h>

main()
{
    FILE *fp1, *fp2;
    char ch;
	
    // open the file for reading
    fp1 = fopen("file1.txt", "r");
    // open the file for writing
    fp2 = fopen("file2.txt", "w");
	
    // Read the contents of the file
    while((ch = getc(fp1)) != EOF)
        putc(ch, fp2);
	
    fclose(fp1);
    fclose(fp2);
    getch();
}
  • STEP 1: Create a new text file and rename it to “file1.txt”.
  • STEP 2: Write some content to this file and save it.
  • STEP 3: Now compile the above C program and run it.

Now a new file will be created with the name “file2.txt” and all the content will be copied from file1.txt to file2.txt.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *