Program 12
Write a
C program to copy a text file to another,
read both the
input file name and target file name.
This program demonstrates file handling operations, error checking, and character-by-character
file copying using standard C library functions for secure file operations.
Algorithm
- Input File Names: Read source and target file names from user
- Open Source File: Open source file in read mode ("r")
- Check Source File: Verify source file opened successfully, exit if error
- Open Target File: Open target file in write mode ("w")
- Check Target File: Verify target file created successfully, close source and exit if error
- Copy Contents: Read each character from source using fgetc()
- Write Character: Write each character to target using fputc()
- Continue Until EOF: Repeat copying until end of file reached
- Close Files: Close both source and target files
- Display Success: Print confirmation message to user
Flowchart
START
→
Input File Names
→
Open Source File
→
Check Source Error
→
Open Target File
→
Check Target Error
→
Copy Characters
→
Close Files
→
STOP
Code
#include <stdio.h>
#include <stdlib.h>
int main() {
char source[100], target[100];
FILE *fs, *ft;
char ch;
// Get file names
printf("Enter source file name: ");
scanf("%s", source);
printf("Enter target file name: ");
scanf("%s", target);
// Open source file
fs = fopen(source, "r");
if (fs == NULL) {
printf("Error: Cannot open source file %s\n", source);
exit(1);
}
// Open target file
ft = fopen(target, "w");
if (ft == NULL) {
printf("Error: Cannot create target file %s\n", target);
fclose(fs);
exit(1);
}
// Copy contents
while ((ch = fgetc(fs)) != EOF) {
fputc(ch, ft);
}
printf("File copied successfully from %s to %s\n", source, target);
// Close files
fclose(fs);
fclose(ft);
return 0;
}