kumar said:
i am bit confused about this code, why does the below while loop is
contineous
how can i come out of the file.
i am using linux machine
You better don't get in the habit of commenting the obvious.
FILE *fp; // file pointer
fp=fopen("file","r");
while(fp!=EOF)// here i am just reading character by character and
This completely off the mark and the compiler would tell so
you if you would raise its warning level to a suitable value.
You are comparing an int to a pointer and that makes no sense
at all. 'fp' will never change (at least as long as you don't
actively asign it a new value) and neither will EOF.
Instead you should check 'fp' for being NULL before using it
- it will be NULL in case opening the file failed.
printing to display
{
fscanf(fp,&ch);
Testing the return value of fscanf() will tell you when you
reached the end of the file. Since you read only a single
item you simply can test it for EOF (but also other problem
with reading the file will make it return EOF, if you want
to know the details use feof() or ferror() to distinguish
between those cases).
But using fscanf() is a bit like shooting sparrows with a canon,
have a look at (f)getc() for a probably much faster function for
reading single characters.
And here putchar() probably is more suitable.
problem is:: At end ,file pointer is pointing to last character and it
The file pointer isn't pointing to a char, maybe some pointer
in a struture 'fp' may be pointing to does (but that's imple-
mentation specific and you shouldn't care about that)
is holding that because of this
the while condition is true
The while condition is only true by accident. You're comparing
apples to bananas and since such a comparison isn't reasonable
you whatever the result is has no value for your program.
so how can i come out of loop
By testing the return values of functions that tell you some-
thing about the fact that the end of the file has been reached.
Typically these are the functions that do the reading and thus
notice that they couldn't read what you asked them to read.
Carefully read their descriptions and you will find it's rather
simple. Don't make unfounded assumptions like that the file
pointer would do anything.
Regards, Jens