I'm trying to read contents from a file "file.txt" and write each character from there to "copy.txt" but I get a weird character at the end of the "copy.txt" file.
I'm trying to open and close the two files and modify the body of the while loop in the program so that the character is no longer put to standard output (stdout).
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
FILE *from, *to;
from = fopen("file.txt", "r");
if (from == NULL)
{
perror("file.txt doesn't exist.");
exit(1);
}
to = fopen("copy.txt", "w");
if (to == NULL)
{
perror("copy.txt doesn't exist.");
exit(1);
}
do
{
c = getc(from);
putc(c, to);
}
while(c != EOF);
fclose(to);
fclose(from);
exit(0);
}
Your Problem lies in this loop:
do
{
c = getc(from);
putc(c, to);
}
while(c != EOF);
What you need to understand is the difference between a do-while
and a while
loop. A while
loop will evaluate the expression BEFORE running the loop (thus the loop runs at least 0 times) and a do-while
loop evaluates AFTER the loop circle (thus running at least one time).
So whats the problem? You read a character, write it to copy.txt
, THEN evaluate if its EOF
and exit the loop or not. Now, what happens when the last char is read from the file? The loop will run one more time, as the last character is NOT EOF
. Your program will read one more character and write to the file. That is the character that you meant.
So in order to fix, you need to evaluate for EOF
BEFORE writing. Here are two attempts, one that will keep your do-while
loop and one that uses a while
loop (more clear):
Do-While Attempt (not pretty and unneccessary if):
do
{
c = getc(from);
if (c != EOF) {
putc(c, to);
}
}
while(c != EOF);
While Attempt:
while ((c = getc(from)) != EOF) {
putc(c, to);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.