Hi guys, am new in C programming. I don't understand the following:
In the below code snippet, input.txt is 30 bytes. When I run the program, output.txt is 31 bytes.
Code:
FILE *fp, *new_fp;
int ch;
if((fp = fopen("input.txt", "rb")) == NULL){
fprintf(stderr, "Error opening file for reading...");
exit(1);
}
if((new_fp = fopen("output.txt", "wb")) == NULL){
fprintf(stderr, "Error opening a new file for writing!");
exit(1);
}
/* I use a while loop to check for FEOF */
while(!feof(fp)){
ch = fgetc(fp);
putc(ch, new_fp);
}
fcloseall();
In another code snippet as shown below, input.txt and output.txt is both 30 bytes.
Code:
FILE *fp, *new_fp;
int ch;
if((fp = fopen("input.txt", "rb")) == NULL){
fprintf(stderr, "Error opening file for reading...");
exit(1);
}
if((new_fp = fopen("output.txt", "wb")) == NULL){
fprintf(stderr, "Error opening a new file for writing!");
exit(1);
}
while(1){
ch = fgetc(fp);
if(!feof(fp)){
fputc(ch, new_fp);
}else{
break;
}
}
As you can see above, the only different is the while looping to copy data from one file to another.
Can someone enlighten me why there is a extra one byte in the first code snippet?
Thanks in advance!