updating binary file containing structs in c, offsets changing to corrupt rest of file

放肆的年华 提交于 2019-12-04 15:02:11

It looks like the problem is occurring because you are performing a read directly following a write with a file that has been opened with the mode r+. The book "C In a Nutshell" states:

If the mode string includes a plus sign, then the mode allows both input and output, and you must synchronize the file position indicator between reading from and writing to the file. Do this by calling fflush() or a file positioning function -- fseek(), fsetpos(), or rewind() -- after writing and before reading, and by calling a file-positioning function after reading and before writing (unless it is certain that you have read to the end of the file).

The issue is in your nested-most while() loop here:

/*** Read occurs here... ***/
while(fread((void*)updateStock,sizeof(stock),1,fout)==1&&!update){  
    printf("position: %ld\n",ftell(fout));
    printf("update stock: %d, %1.2lf\n",updateStock->number,updateStock->price);
    if(updateStock->number==currStock->number){

        printf("updating stock with new price: %1.2lf\n",currStock->price);
        currPos = ftell(fout);
        printf("ftell = %d\n",currPos);
        fseek(fout,currPos-sizeof(stock),SEEK_SET);
        printf("ftell after seek: %ld\n",ftell(fout));

        /** Write occurs here but...
            during the next while() check a read is immediately performed. **/
        fwrite(currStock,sizeof(stock),1,fout);
        update = 1;
    }

I added the following immediately after your fwrite() and it seems to be working...

fflush(fout);

Also, just a side note. Your currPos is an int and ftell() returns a long (there is not guarantee that your int will hold a long value).

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!