Ad Space
This question has two parts. Here are the programs for both operations.
Program 1: Copy contents from one file to another
This program reads one file (e.g., source.txt) character by character and writes each character to a new file (destination.txt).
#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *sourceFile, *destFile;
char ch;
// --- Create a dummy source file for testing ---
sourceFile = fopen("source.txt", "w");
if(sourceFile == NULL) {
printf("Error creating source.txt\n");
return 1;
}
fprintf(sourceFile, "This is the content\nof the source file.\nHello World!");
fclose(sourceFile);
// ---------------------------------------------
// Open source file for reading
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file 'source.txt'\n");
exit(1);
}
// Open destination file for writing
destFile = fopen("destination.txt", "w");
if (destFile == NULL) {
printf("Error: Could not create destination file 'destination.txt'\n");
fclose(sourceFile);
exit(1);
}
// Read from source and write to destination, character by character
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}
printf("File copied successfully!\n");
printf("Check 'destination.txt' for the copied content.\n");
// Close both files
fclose(sourceFile);
fclose(destFile);
return 0;
}
Program 2: Merge two files into a third file
This program reads the contents of file1.txt and appends them to merged.txt, then reads the contents of file2.txt and appends them to merged.txt.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *file1, *file2, *mergedFile;
char ch;
// --- Create dummy file 1 ---
file1 = fopen("file1.txt", "w");
if(file1 == NULL) { printf("Error.\n"); return 1; }
fprintf(file1, "Content from file 1.\nSecond line of file 1.\n");
fclose(file1);
// --- Create dummy file 2 ---
file2 = fopen("file2.txt", "w");
if(file2 == NULL) { printf("Error.\n"); return 1; }
fprintf(file2, "Content from file 2.\nThis is the last line.\n");
fclose(file2);
// ---------------------------------
// --- Open files for merging ---
file1 = fopen("file1.txt", "r");
file2 = fopen("file2.txt", "r");
// Open merged file in "w" (write) mode to create it
mergedFile = fopen("merged.txt", "w");
if (file1 == NULL || file2 == NULL || mergedFile == NULL) {
printf("Error opening one or more files!\n");
exit(1);
}
// 1. Copy content from file1 to mergedFile
while ((ch = fgetc(file1)) != EOF) {
fputc(ch, mergedFile);
}
fprintf(mergedFile, "\n"); // Add a newline for separation
// 2. Copy content from file2 to mergedFile
while ((ch = fgetc(file2)) != EOF) {
fputc(ch, mergedFile);
}
printf("Files merged successfully into 'merged.txt'!\n");
// Close all files
fclose(file1);
fclose(file2);
fclose(mergedFile);
return 0;
}
Ad Space