Search code examples
cfilestructurebinaryfilessymbol-table

Why fread returns Zero and when the files has contents


im trying to read a content of the file "sym.dat" even thru file has contents fread returns zero and i tried using ferror too but it didnt show any error.

FILE *fp;
fp=fopen("sym.dat","ab");

struct node a;
    fseek(fp, 0L, SEEK_SET); 

while((fread(&a,sizeof(struct node),1,fp))==1)
{

printf("bello");

}}

it returns 0


Solution

  • doing

     fp=fopen("sym.dat","ab");
    

    you open the file to write in it from its end, not to read in it, so the test in while((fread(&a,sizeof(struct node),1,fp))==1) is immediately false and you do not print "bello"

    do

    fp=fopen("sym.dat","rb");
    

    and check fp is not NULL.

    The fseek is useless, when you open it you are at its beginning

    Do not forget to close the file


    If you need to read and write in it open it with the flags "rb+", the fseek is still useless.