This blog is under construction

Monday 29 July 2013

C program to copy a file from one location to another

Write a C program to copy one file to another.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        int ch;
        FILE *fp1, *fp2;
        char src[MAX], dest[MAX];

        /* get the source file name from the user */
        printf("Enter your source file name:");
        fgets(src, MAX, stdin);
        src[strlen(src) - 1] = '\0';

        /* get the destination file name from the user */
        printf("Enter your destination file name:");
        fgets(dest, MAX, stdin);
        dest[strlen(dest) - 1] = '\0';

        /* open the source file in read mode */
        fp1 = fopen(src, "r");
        /* open the destination file in write mode */
        fp2 = fopen(dest, "w");

        /* error handling */
        if (!fp1) {
                printf("Unable to open source file to read!!\n");
                fclose(fp2);
                return 0;
        }

        if (!fp2) {
                printf("Unable to open destination file to write\n");
                return 0;
        }

        /* copying contents of source file to destination file */
        while (!feof(fp1)) {
                ch = fgetc(fp1);
                fputc(ch, fp2);
        }

        /* closing the opened files */
        fclose(fp1);
        fclose(fp2);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls
  a.out  data.txt 

  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your source file name:data.txt
  Enter your destination file name:./output.txt

  jp@jp-VirtualBox:~/$ ls
  a.out  data.txt  output.txt

  jp@jp-VirtualBox:~/$ cat output.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.






SEE ALSO

    No comments:

    Post a Comment