While doing filing im stuck here.The condition of the while loop is not working.The compiler says cannot convert int to FILE*.
while(pFile!=EOF);
Should i typecase the pFile to int?I tried that but it did not worked.Thanks in advance.
The complete code is:
int main()
{
char ch;
char name[20];
FILE *pFile;
int score;
pFile=fopen("database.txt","r");
if(pFile!=NULL)
{
while(pFile!=EOF);
{
fscanf(pFile,"%c",ch);
}
}
else
printf("Cant open the file.......");
fclose(pFile);
return 0;
}
First, you do not want to use
while (!feof(pFile))— ever! Doing so will almost inevitably lead to an error where the last data you read from the file appears to be read twice. It’s possible to make it work correctly, but only by adding another check in the middle of the loop to exit when EOF is reached — in which case, the loop condition itself will never be used (i.e., the other check is the one that will actually do the job of exiting the loop).What you normally do want to do is check for EOF as you read the data. Different functions indicate EOF in different ways.
fgetssignals failure (including EOF) by returning NULL. Most others (getc, fgetc, etc.) do return EOF, so you typically end up with something like this:or:
With scanf, checking for success is a little more complex — it returns the number of successful conversions, so you want to make sure that matches what you expected. For example:
In this case I’ve used
1because I specified 1 conversion in the format string. It’s also possible, however, for conversion to fail for reasons other than EOF, so if this failes, you’ll frequently want to checkfeof(pFile). If it returns false, do something like reading the remainder of the line, showing it to the user in a warning message, and then continuing to read the rest of the file.