Copy the Content one File to Other File in C Programming

Copy the Content one File to Other File in C Programming

Posted on

This C program prompts the user to enter the name of a source file, opens the file in read mode, then prompts the user to enter the name of a destination file, and opens the file in write mode. It then copies the contents of the source file to the destination file character by character using a loop that reads each character from the source file and writes it to the destination file until the end of the source file is reached.

# C Program


#include 
#include 
int main()
{
    FILE *fp1, *fp2;
    char filename[100], p;
    printf("Enter your Source file name : ");
    scanf("%s", &filename);

    fp1=fopen(filename, "r");
    if(fp1==NULL)
    {
        printf("Can't be open your file");
        exit(0);
    }
    printf("Enter Your destionation file name : ");
    scanf("%s", filename);
    fp2=fopen(filename, "w");
    if(fp2==NULL)
    {
        printf("Can't be open your file");
        exit(0);
    }
    p=fgetc(fp1);
    while (p!=EOF)
    {
        fputc(p, fp2);
        p=fgetc(fp1);
    }
    printf("Contant copy success full file 1 to file 2");
    fclose(fp1);
    fclose(fp2);

    return 0;
    
}

Here is a breakdown of the program’s logic:

  1. Declare two file pointers, fp1 and fp2, of type FILE.
  2. Declare a character variable, p, to store the characters read from the source file.
  3. Prompt the user to enter the name of the source file using printf and scanf.
  4. Open the source file in read mode using fopen and store the file pointer in fp1.
  5. Check if the file pointer fp1 is NULL, which indicates that the file could not be opened. If it is NULL, print an error message and exit the program using exit(0).
  6. Prompt the user to enter the name of the destination file using printf and scanf.
  7. Open the destination file in write mode using fopen and store the file pointer in fp2.
  8. Check if the file pointer fp2 is NULL, which indicates that the file could not be opened. If it is NULL, print an error message and exit the program using exit(0).
  9. Read a character from the source file using fgetc and store it in the variable p.
  10. While the character read is not equal to EOF (end of file), write the character to the destination file using fputc and read the next character from the source file using fgetc.
  11. When the end of the source file is reached, print a message indicating that the contents were successfully copied from the source file to the destination file.
  12. Close both file pointers using fclose.
  13. Return 0 to indicate successful program completion.

Note: It is recommended to use fgets() and fputs() for reading and writing lines of text respectively, instead of fgetc() and fputc() which are used for reading and writing individual characters.