how can i stop the reading cycle on eof:
while(f!=EOF) tells me comparison betwen pointer and integer
thank you!
Printable View
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);
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.
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...
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]
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".Quote:
Originally Posted by spank
FAQ > Explanations of... > Why it's bad to use feof() to control a loop
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;
}