📁Beginner

Read and Write Content Between Files

File transfer

Read content from one file and write it to another file.

Program Code

file_read_write.c
C
1#include <stdio.h>
2
3int main() {
4 FILE *source, *dest;
5 char ch;
6
7 source = fopen("source.txt", "r");
8 if (source == NULL) {
9 printf("Cannot open source file!\n");
10 return 1;
11 }
12
13 dest = fopen("destination.txt", "w");
14 if (dest == NULL) {
15 printf("Cannot create destination file!\n");
16 fclose(source);
17 return 1;
18 }
19
20 printf("Copying file contents...\n\n");
21
22 // Copy character by character
23 while ((ch = fgetc(source)) != EOF) {
24 fputc(ch, dest);
25 putchar(ch); // Also print to console
26 }
27
28 printf("\n\nFile copied successfully!\n");
29
30 fclose(source);
31 fclose(dest);
32
33 return 0;
34}
Output

Copying file contents...

 

Hello, this is the source file.

It contains multiple lines.

All content will be copied.

 

File copied successfully!

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples