Index « Previous Next »

Question

Write a program which copy one file contents to another. Your program should asked the file names from user.

Source Code

#include <stdio.h>

int main()
{
    char in_name[80], out_name[80];
    FILE *in_file,  *out_file;
    int ch;

    printf("Enter file name to be copied:\n");
    scanf("%s", in_name);
    printf("Enter output filename:\n");
    scanf("%s", out_name);

    in_file = fopen(in_name, "r");

    if (in_file == NULL)
        printf("Can't open %s for reading.\n", in_name);
    else
    {
        out_file = fopen(out_name, "w");
        if (out_file == NULL)
            printf("Can't open %s for writing.\n", out_name);
        else
        {
            while ((ch = fgetc(in_file)) != EOF)
            {
                fputc(ch, out_file);
            }
            printf("File has been copied.\n");
            fclose(out_file);
        }
        fclose(in_file);
    }
    return 0;
}

Output

Enter file name to be copied:
sample.txt
Enter output filename:
newfile.txt
File has been copied.