C program to copy the contents of one file to another file?



C Files I/O − Create, Open, Read, Write and Close a File

C File management

A File can be used to store a large volume of persistent data. Like many other languages 'C' provides the following file management functions,

  • Creation of a file
  • Opening a file
  • Reading a file
  • Writing to a file
  • Closing a file

Following are the most important file management functions available in 'C,'

functionpurpose
fopen ()Creating a file or opening an existing file
fclose ()Closing a file
fprintf ()Writing a block of data to a file
fscanf ()Reading a block data from a file
getc ()Reads a single character from a file
putc ()Writes a single character to a file
getw ()Reads an integer from a file
putw ()Writing an integer to a file
fseek ()Sets the position of a file pointer to a specified location
ftell ()Returns the current position of a file pointer
rewind ()Sets the file pointer at the beginning of a file


Input:
sourcefile = x1.txt
targefile = x2.txt
Output: File copied successfully.

Explanation

In this program we will copy a file to another file, firstly you will specify a file to copy. We will open the file and then read the file that we wish to copy in "read" mode and target file in "write" mode.

Example

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   char ch;// source_file[20], target_file[20];
   FILE *source, *target;
   char source_file[]="x1.txt";
   char target_file[]="x2.txt";
   source = fopen(source_file, "r");
   if (source == NULL) {
      printf("Press any key to exit...
");       exit(EXIT_FAILURE);    }    target = fopen(target_file, "w");    if (target == NULL) {       fclose(source);       printf("Press any key to exit...
");       exit(EXIT_FAILURE);    }    while ((ch = fgetc(source)) != EOF)       fputc(ch, target);    printf("File copied successfully.
");    fclose(source);    fclose(target);    return 0; }

Advertisements