C program to read and write to the file


 #include <stdio.h>

#include <stdlib.h>


int main() {

    FILE *fp1, *fp2;

    char filename1[100], filename2[100], c;


    printf("Enter the name of the input file: ");

    scanf("%s", filename1);


    // open input file for reading

    fp1 = fopen(filename1, "r");

    if (fp1 == NULL) {

        printf("Error opening file %s\n", filename1);

        exit(1);

    }


    printf("Enter the name of the output file: ");

    scanf("%s", filename2);


    // open output file for writing

    fp2 = fopen(filename2, "w");

    if (fp2 == NULL) {

        printf("Error opening file %s\n", filename2);

        exit(1);

    }


    // read from input file and write to output file

    while ((c = fgetc(fp1)) != EOF) {

        fputc(c, fp2);

    }


    printf("Contents copied to %s\n", filename2);


    // close files

    fclose(fp1);

    fclose(fp2);


    return 0;

}

In this program, we start by declaring two file pointers fp1 and fp2 to represent the input and output files, respectively. We also declare two character arrays filename1 and filename2 to hold the names of the input and output files, respectively. We prompt the user to enter the name of the input file and open it for reading using fopen.

Next, we prompt the user to enter the name of the output file and open it for writing using fopen. We then read characters from the input file using fgetc and write them to the output file using fputc. This process continues until the end of the input file is reached, at which point we close both files using fclose.

Finally, we print a message indicating that the contents have been copied to the output file, and return 0 to indicate successful execution of the program.

Post a Comment

0 Comments