Copy Text File using C Program


#include<stdio.h>

int main(int argc, char* argv[]){
    FILE *sfp;                   // Source File Pointer
    FILE *tfp;                   // Target File Pointer
    char SourceFilename[255];    // Stores the source file name
    char TargetFilename[255];    // stores the target file name
    char ch;                     // used to read charecter
                                 //       from source file name

    /* Get sourcefile name and targetfile name from the user */
    printf("\nEnter Soucefile Name: ");
    gets(SourceFilename);
    fflush(stdin);
    printf("Enter Targetfile Name (NOTE : If Targetfile already exists, its content will be overwritten): ");
    gets(TargetFilename);

    /* Open source file in read mode and target file in write mode */
    sfp=fopen(SourceFilename,"r");
    if(sfp==NULL){
        printf("\nERROR: Failed to open %s in read mode. Closing the program...",SourceFilename);
        return;
    }
    tfp=fopen(TargetFilename,"w");
    if(tfp==NULL){
        printf("\nERROR: Failed to open %s in write mode. Closing the program...",TargetFilename);
        return;
    }

    /* read charecter by charecter from sourcefile
       and write those charecters accordingly in targetfile */
    while(1){
        ch=fgetc(sfp);
        if(ch==EOF){
            break;
        }else{
            fputc(ch,tfp);
        }
    }

    /* close file pointers */
    fclose(sfp);
    fclose(tfp);
}

No comments:

Post a Comment