Jim said:
Hi There,
I'm trying to read a file character by character. When I write the
file out, there is one extra character
I bet you're using feof (wrongly).
which shows on the screen as a
solid circle with a small question mark in the middle.
Here is what I have:
infile = fopen("encrypted.txt", "r");
outfile = fopen("plain.txt", "w");
What if either (or both) of these files fails to open?
>
while(!feof(infile)) {
ch = fgetc(infile);
fputc(ch, outfile);
}
fclose(infile);
fclose(outfile);
Can someone please tell me why this character is getting added to the
outfile?
feof is reactive, not predictive. It won't yield a non-zero result until
you've actually tried to read past the end of the file.
The fix is to stop using feof (or at least, to stop using it in quite that
way):
#include <stdio.h>
int main(int argc, char **argv)
{
if(argc == 3)
{
FILE *infile = fopen(argv[1], "r");
if(infile != NULL)
{
FILE *outfile = fopen(argv[2], "w");
if(outfile != NULL)
{
int ch;
while((ch = getc(infile)) != EOF)
{
putc(ch, outfile);
}
if(ferror(infile))
{
fprintf(stderr, "error reading %s\n", argv[1]);
}
if(ferror(outfile))
{
fprintf(stderr, "error writing %s\n", argv[2]);
}
if(fclose(outfile) != 0)
{
fprintf(stderr, "error closing %s\n", argv[2]);
}
}
else
{
fprintf(stderr, "error opening %s\n", argv[2]);
}
fclose(infile);
}
else
{
fprintf(stderr, "error opening %s\n", argv[1]);
}
}
else
{
fprintf(stderr, "please specify input and output filenames\n");
}
return 0;
}
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999