I am trying to copy characters from one text file directly to another using fscanf/fprintf w/ %c but I am being left with an extra white space character at the very end of the file.
Is there a way I can trim the last whitespace character from the output file or tell my function to ignore the very last white space?
Also my constraints dictate that I am not allowed to use an array to parse any read characters. My program needs to read and copy directly from the input file to the output file.
Here is my code below.
void copyFile(FILE* inputStream, FILE* outputStream){
while(!feof(inputStream)) {
int readCorrectly;
char readChar;
readCorrectly = fscanf(inputStream, "%c", &readChar);
if (readCorrectly) {
fprintf(outputStream, "%c", readChar);
}
}
}
The problem here is that the end-of-file indicator is set when you attempt to read past the end of the file.
To resolve this, you need to add a check after the fscanf
.
E.g.
if (feof(inputStream)) {
break;
}
In doing so, you could also replace your while condition with an infinite loop, i.e. while (1)
.
There are more explanations about how feof
works here:
How feof() works in C