Example : Write a C program to copy the contents of one file to another file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fp1, *fp2; // Declare two file pointer fp1 & fp2 char filename[50], c; printf("Enter the filename to open for reading "); scanf("%s", filename); fp1 = fopen(filename, "r"); // Open file for read if (fp1 == NULL) { printf("\n Cannot open file %s ", filename); exit(0); } printf("\n Enter the filename to open for writing "); scanf("%s", filename); fp2 = fopen(filename, "w"); // Open file for write if (fp2 == NULL) { printf("\n Cannot open file %s", filename); exit(0); } c = fgetc(fp1); // Read contents from file while (c != EOF) { fputc(c, fp2); // write character to another file c = fgetc(fp1); // Read contents from file } printf("\nContents copied to %s", filename); fclose(fp1); // closing file fclose(fp2); // closing file return 0; } |
OUTPUT
| Enter the filename to open for reading A.txt Enter the filename to open for writing B.txt Contents copied to B.txt |
Example : Write a C program to appends the content of file at the end of another file. Or Example : Write a C program to merge two files into third file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <stdio.h> #include <stdlib.h> int main() { FILE *fp1, *fp2, *ftemp; char ch, file1[20], file2[20], file3[20]; printf("Enter name of first file "); gets(file1); printf("\n Enter name of second file "); gets(file2); printf("\n Enter name to store merged file "); gets(file3); fp1 = fopen(file1, "r"); fp2 = fopen(file2, "r"); if (fp1 == NULL || fp2 == NULL) { printf("\n Cannot open file "); exit(0); } ftemp = fopen(file3, "w"); if (ftemp == NULL) { printf("\n Cannot open file %s ", file3); exit(0); } while ((ch = fgetc(fp1)) != EOF) fputc(ch, ftemp); while ((ch = fgetc(fp2) ) != EOF) fputc(ch, ftemp); printf("\n Two files merged successfully in file =", file3); fclose(fp1); fclose(fp2); fclose(ftemp); return 0; } |
| Enter name of first file A.txt Enter name of second file B.txt Enter name to store merged file Merge.txt Two files merged successfully in file= Merge.txt |
Example: Write a C program … Read more