how can i stop the reading cycle on eof:
while(f!=EOF) tells me comparison betwen pointer and integer
thank you!
how can i stop the reading cycle on eof:
while(f!=EOF) tells me comparison betwen pointer and integer
thank you!
I'm guessing you're trying to read one character at a time:
Code:int ch; while((ch = fgetc(f)) != EOF) printf("I read the character: %c\n", ch);
If you understand what you're doing, you're not learning anything.
i`m trying to do smthing like this to read in a string a lineCode:while("f!=EOF") { fscanf(f,"%s",a); printf("%s\n",a); }
Try while(fgets(a, buffer_size, f)) instead.
If you understand what you're doing, you're not learning anything.
but i don't know the size of the line... its variable
It's not the size of the line you're supplying, it's the size of the buffer in which you want to store the line...
If you understand what you're doing, you're not learning anything.
You could useassuming that f is a FILE *. Also, in your fscanf() calls, you ought to be passing a pointer to the destination.Code:while (!feof(f)) { ... }
[edit]
I do prefer fgets() and sscanf() to the use of fscanf(); but that's been covered many places many times.[/edit]
[edit2]
As is pointed out below, feof() is not a good way to control the loop, and for good reasons. My contribution is simply in answer to the original query where the attemtp to use "if (f == EOF)" was being discussed.[/edit2]
Last edited by filker0; 01-20-2006 at 01:57 PM. Reason: Add a comment...
Insert obnoxious but pithy remark here
The more correct idiom is "while successfully obtaining expected input" (and itsme86 has already posted such an example) rather than "while not having encountered one of several possible failures the last time".Originally Posted by spank
FAQ > Explanations of... > Why it's bad to use feof() to control a loop
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Here's how to use fgets():
BUFSIZ is defined in <stdio.h>, and it's usually about 512. You can use any number that you like.Code:#include <stdio.h> int main(int argc, char *argv[]) { char s[BUFSIZ]; FILE *fp; if(argc <= 1) { fprintf(stderr, "\nusage: printfile file_to_print\n"); return 1; } if((fp=fopen(argv[1], "rt")) == NULL) { fprintf(stderr, "\nCan't open file \"%s\"\n", argv[1]); return 1; } while(fgets(s, sizeof(s), fp)) { printf("%s", s); } fclose(fp); return 0; }
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.