简体   繁体   English

fread() 在 C 中 fseek() 和 fwrite() 后不起作用

[英]fread() not working after fseek() with fwrite() in C

In my program i make a binary file contains structs (each struct contains one integer)...and i put 3 structs in the file...i want first to create the file...then close it..then reopen it as "rb+" mode...and i want to read the structs from the file and change its value (member data) and rewrite it at the same file as this way:在我的程序中,我制作了一个包含结构体的二进制文件(每个结构体包含一个整数)……我在文件中放入了 3 个结构体……我想首先创建文件……然后关闭它……然后重新打开它“rb+”模式......我想从文件中读取结构并更改其值(成员数据)并以这种方式在同一文件中重写它:

#include <stdio.h>
main()
     {
         int i;

         struct
         {
             int data;
         }x;  

         FILE* myfile=fopen("d:\\text.bin","wb");

         for(i=1;i<4;i++)
         {
              x.data=i;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

         myfile=fopen("d:\\text.bin","rb+");

         for(i=0;i<3;i++)
         {
              fread(&x,sizeof(x),1,myfile);
              printf("%d\n",x.data);
              fseek(myfile,-sizeof(x),SEEK_CUR);
              x.data=2*x.data;
              fwrite(&x,sizeof(x),1,myfile);
         }

         fclose(myfile);

     }`

but...my output in stdout file was: 1 2 2但是...我在标准输出文件中的输出是:1 2 2

it should be 1 2 3应该是 1 2 3

BUT...when i added fseek(myfile,0,SEEK_CUR);但是...当我添加 fseek(myfile,0,SEEK_CUR); after fwrite(&x,sizeof(x),1,myfile);....it is run correctly and output : 1 2 3在 fwrite(&x,sizeof(x),1,myfile);....之后它运行正确并输出:1 2 3

can any one help me ???谁能帮我 ???

You just need to tell the program to switch the write mode to the read mode so您只需要告诉程序将写入模式切换到读取模式即可

fseek(myfile,0,SEEK_CUR); 

It is necessary if you don't, you just get the same result with no change at all, or you might get an infinite loop.如果您不这样做,则有必要,您只会得到相同的结果而根本没有改变,否则您可能会陷入无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM