Originally Posted by
WoodSTokk
I don't know if you talking about this line
Code:
while (!(feof(fp)))
or this line
Code:
while ((c = fgetc(fp)) != EOF )
Thats two completely different things.
In first case, the function 'feof' checks the end-of-file indicator of that stream and has nothing to do with the last read character.
In second case, the returned value of the function 'fgetc' will be assigned to the variable 'c' and thereafter the value of 'c' will be checked against the macro 'EOF'.
It can be, that the truncated value stored in 'c' represent also 'EOF', but it can also be that 'EOF' was not meant.
exactly, that is what I am saying, they two completely different things.,
that is one cause of the problem, because you check for EOF first, and that returns the marker feof or ferror so you can check that next if you want to know the why it stopped.
this is wrong:
Code:
#include <stdio.h>
int main (int argc, char **argv)
{
char c;
int i = 0;
char string[100]; // max string length is 100. last spot reserved for '\0'
//string[100] = '\0';
FILE *fp;
fp = fopen(argv[1], "r"); // the input file
while (!(feof(fp))) {
c = fgetc(fp) ;
string[i] = c;
i++;
}
string[i] = '\0';
printf("%s %d\n",string, i);
fclose(fp);
return 0;
}
you are always going to get one 'bad' ch printed out because it runs one more after ending at 'eof'. because feof is the return value not the check.
even their example of how to run it and check for EOF is not like yours, because when it reaches EOF it returns,
feof or ferror then you check for that next,
LIKE this:
it is used to see why it stopped reading the file.
Code:
include <stdio.h>
int main (int argc, char **argv)
{
char c;
int i = 0;
char string[100]; // max string length is 100. last spot reserved for '\0'
FILE *fp;
fp = fopen(argv[1], "r"); // the input file
while ((c = fgetc(fp)) != EOF ) {
string[i] = c;
i++;
}
string[i] = '\0';
if (feof(fp) )
printf("\n feof returned \n Normal eof of stream\n");
else if (ferror(fp))
printf(" \ntferror returned \n errored before eof \n");
fclose(fp);
printf("\n%s %d\n",string, i);
return 0;
}
results
Code:
userx@~/bin <> ./a.out input_file
feof returned
Normal eof of stream
this
is
an
input
file
this is an input file string.
53
using this way
Code:
while (!(feof(fp)))
is telling it to keep trying to read it while it is not a normal EOF
----
as far as the c having to be a int or char you are correct it works both ways, I checked it.