Originally Posted by
userxbw
now you tell me that example is wrong by now stating I and others should not use that
Where have I told you that this is wrong???
Originally Posted by
userxbw
which equates to the same as this,
Code:
while ( c = fgetc(pfile) != EOF ) {
if (c == '$')
printf (" got it ($)\n");
}
which you used to show this is how to do it, now you're saying it is not. Why are you now contradicting yourself, for one?
I dont know where you find a contradiction. Both examples uses 'fgetc' and both assign the returned value to a int-variable.
BTW, you should set the assignment in perentheses, so that the compiler knows what operation comes first.
Code:
while ((c = fgetc(pfile)) != EOF) {
Originally Posted by
userxbw
The problem in this thread has nothing to do with 'fgetc'.
There is no contradiction because nobody use 'feof' there and the returned value of 'fgetc' will be assigned to a int-variable.
Originally Posted by
userxbw
Your snippet is to short. Here is the full code
Code:
char buffer[500];
FILE *fp;
int lineno = 0;
if ((fp = fopen("myinputfile.txt","r")) == NULL)
{
printf("Could not open myinputfile.txt\n");
exit(1);
}
while ( !feof(fp))
{
// read in the line and make sure it was successful
if (fgets(buffer,500,fp) != NULL)
{
printf("%d: %s",lineno++,buffer);
}
}
You can see in this reference that the autor uses 'fgets' (and not 'fgetc') and he/she dont use it blindly.
The 'fgets'-call is encapsulated in a if-contition. This means that the result will only be used if it is valid.
You can also use 'feof' as your while-contition if you use 'fgetc' inside the loop-body. But then, you should also check the returned value.
Code:
// correct 'feof'-variant
while (!(feof(fp))) {
if ((c = fgetc(fp)) != EOF) {
string[i++] = c;
}
}
You can also shorten the code from you reference
Code:
while (fgets(buffer,500,fp) != NULL)
{
printf("%d: %s",lineno++,buffer);
}
The point is in this case, that you have a extra check if you use 'feof'.
Avoiding 'feof' and set the if-contition as while-contition make the code smaller and cleaner (and possibly faster).
Originally Posted by
userxbw
again these two examples show what I am now suggesting as a truth. it has to be, because both deferent ways are being used to read a file,
and are considered by the others to be a right way of doing it.
If you expect errors, 'ferror' is the best way to catch it.
Originally Posted by
userxbw
Just so you know it looks like you're going to have to inform
the entire programming community of your findings.
I have not finding them, it is defined in the C-Standard. Experienced programmer know this allready.
Originally Posted by
userxbw
It looks like their is more then one solution as long as the check for End Of File is included into it while reading the file.
Correct! But a programmer should use the simplest way to reach the goal.
As i show you above, you can use 'feof', but you then need a second check.