- Asked 2/16
- 2074 Chaitra · 8 marks
- 2072 Chaitra · 6 marks
Copy contents of one file to another
Short answer
Open source file in read mode and destination in write mode, checking for NULL. Read characters with fgetc until EOF, writing each with fputc. Use int for the character to detect EOF. Close both files.
Write a program in C to copy content of one file source.txt to another destination.txt. (Read information of a file named "data.txt" and write its contents to another file "record.txt".)
Logic.
- Open the source file in read mode
"r"and the destination in write mode"w", checking both forNULL. - Read one character at a time with
fgetc()untilEOFand write it withfputc(). - Close both files.
The variable that holds the character is an int (not char), so that EOF can be detected correctly. The same program works for "data.txt" to "record.txt" by changing the two file names.
#include <stdio.h>
int main(void)
{
FILE *src, *dst;
int ch;
src = fopen("source.txt", "r");
if (src == NULL) {
printf("Cannot open source.txt\n");
return 1;
}
dst = fopen("destination.txt", "w");
if (dst == NULL) {
printf("Cannot create destination.txt\n");
fclose(src);
return 1;
}
while ((ch = fgetc(src)) != EOF) /* read one character at a time */
fputc(ch, dst);
fclose(src);
fclose(dst);
printf("File copied successfully\n");
return 0;
}
Sample run (source.txt has three lines; destination.txt has the same three lines afterwards)
File copied successfully
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- RECORD.txt item cost with VAT · Computer Programming, chapter 10
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- 96 students record; pass marks · Computer Programming, chapter 10
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- INVENTORY file of items · Computer Programming, chapter 10
- Employee text file; sort into binary file · Computer Programming, chapter 10
- File stream; student binary file program · Object Oriented Programming, chapter 8
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8
- 8085 ALP: copy data within a range · Microprocessor, chapter 2
- Pycnometer data, water content, γsub · Soil Mechanics, chapter 2