Home

A program to copy one file to another

C Programming Language 115

Program

#include <stdio.h>

void main()
{
    char ch;
    FILE *fp1, *fp2;

    fp1 = fopen("file12.txt", "r");
    if (fp1 == NULL)
    {
        printf("Error: unable to open file1.txt\n");
        return;
    }

    fp2 = fopen("file2.txt", "w");
    if (fp2 == NULL)
    {
        printf("Error: unable to create file2.txt\n");
        return;
    }

    while ((ch = fgetc(fp1)) != EOF)
    {
        putc(ch, fp2);
    }
    fclose(fp1);
    fclose(fp2);

    printf("File copied successfully. Contents of file2.txt are...\n");

    fp2 = fopen("file2.txt", "r");
    while ((ch = fgetc(fp2)) != EOF)
    {
        printf("%c", ch);
    }
    fclose(fp2);

    printf("\n");
}

Result

File copied successfully. Contents of file2.txt are...
hello world from file1


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments