You are here

C program to copy a file

C program to copy a file: This program copies a file, firstly you will specify a file to copy, and then you will enter name and extension of target file . We will open the file that we wish to copy in "read" mode and target file in "write" mode.

C programming code

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6.    char ch, source_file[20], target_file[20];
  7.    FILE *source, *target;
  8.  
  9.    printf("Enter name of file to copy\n");
  10.    gets(source_file);
  11.  
  12.    source = fopen(source_file, "r");
  13.  
  14.    if (source == NULL)
  15.    {
  16.       printf("Press any key to exit...\n");
  17.       exit(EXIT_FAILURE);
  18.    }
  19.  
  20.    printf("Enter name of target file\n");
  21.    gets(target_file);
  22.  
  23.    target = fopen(target_file, "w");
  24.  
  25.    if (target == NULL)
  26.    {
  27.       fclose(source);
  28.       printf("Press any key to exit...\n");
  29.       exit(EXIT_FAILURE);
  30.    }
  31.  
  32.    while ((ch = fgetc(source)) != EOF)
  33.       fputc(ch, target);
  34.  
  35.    printf("File copied successfully.\n");
  36.  
  37.    fclose(source);
  38.    fclose(target);
  39.  
  40.    return 0;
  41. }

Download File copy program.

Output of program:
Output of C program to copy a file