i'm having troubles loading data file. i've put cout<<"entered while loop" when reading , keeps repeating until crashing, not showing data of file.
this part of code find relevant question, if needed i'll provide more informations:
struct book { char name[50]; int bookid; }; struct writter { char name[30]; int writterid, bookamount; struct book book[20]; }; struct publisher { char name[20]; int publisherid, qtautor; writter writter[30]; }; publisher publisher[20]; void savingdata(){ fflush(stdin); if((arquivo = fopen("contact.dat","wb+")) !=null){ cout<<"it enters write part"<<endl;//just checking if enters write part fwrite(&publisher,sizeof(publisher),1,arquivo); fclose(arquivo); } else{ cout<<"error: file cannot opened"; } }//savingdata void loadingdata(){ fflush(stdin); if((arquivo = fopen("contact.dat","rb+")) !=null){ while(!feof(arquivo)){ fread(&publisher,sizeof(publisher),1,arquivo); if(!feof(arquivo)){ cout<<"entered while loop"; }//if }//while fclose(arquivo); }//if else{ cout<<"error: file cannot opened"; } }
i hope didn't forget translate anything.
edit: did sam varshavchik , took fclose out. appears 1 time entered, information on file still not loaded. on file have 1 publisher, 1 writter , 2 books. write names on structs, else added increment. this print of file:
fclose(arquivo);
on first iteration of while
loop, file
closed. once it's closed, file
no longer valid. next thing happen is:
while(!feof(arquivo)){
... try check file
status again, check if iteration of loop should happen. file
no longer valid; hence undefined behavior.
your bug code continues use file
, after closed. once call fclose
, it's game over. can't touch file
object, or refer it, in way. gone. ceased exist. no more. joined choir-invisible. it's ex-file
.
Comments
Post a Comment