Reputation: 25
I'm trying to copy contents of a text file to another text file but my code doesn't work. I've recently started to work with text files so i can not find where the problem is and i don't know how can i solve it. Can you help me please? Here is my code.
#include <stdio.h>
void PrintFileContent(FILE* fptr);
void copy_file(FILE* fptr, FILE* fptr2);
int findNumberofChar(FILE* fptr);
int main() {
FILE *first, *second;
first = fopen("first.txt","r");
second = fopen("second.txt","w+");
PrintFileContent(first);
copy_file(first, second);
PrintFileContent(second);
return 0;
}
void PrintFileContent(FILE* fptr){
char txt;
txt = fgetc(fptr);
while(txt != EOF){
printf("%c", txt);
txt = fgetc(fptr);
}
}
void copy_file(FILE* fptr, FILE* fptr2){
char temp;
temp = fgetc(fptr);
while(temp != EOF){
fputc(temp, fptr2);
temp = fgetc(fptr);
}
}
Upvotes: 1
Views: 63
Reputation: 14491
The 'main' program should rewind the file pointers, before reusing them. Otherwise, the file points are at the end of the content, and the copy_file and the 2nd printFile will not do anything:
int main() {
FILE *first, *second;
first = fopen("first.txt","r");
second = fopen("second.txt","w+");
PrintFileContent(first);
rewind(first) ;
copy_file(first, second);
rewind(second) ;
PrintFileContent(second);
return 0;
}
Upvotes: 3