c - 为什么 fwrite 不覆盖我在 wb+ 中的数据?

标签 c binary

我用 C 编写了一个小程序,用于在二进制文件中创建学生列表。我调用函数 fsearch()(如下)来搜索指定的学生并更改他的数据,但数据似乎没有被修改。

// the file is opened in mode "wb+"
int fsearch(FILE *f)
{
    student s;
    float matsearch;
    printf("enter the matricule you want to find ");
    scanf("%f",&matsearch);
    rewind(f); // starting the search from the beginning
    while(fread(&s,sizeof(student),1,f)==1 && s.mat!=matsearch);
    if(s.mat==matsearch)
    {
        printf("we found what searched for\n");
        printf("name: %s\n",s.fname);
        printf("last name: %s\n",s.lname);
        printf("matricule: %.f\n",s.mat);
        fseek(f,-sizeof(student),SEEK_CUR);     
        student a;
        scanf("%s",&(a.fname));
        scanf("%s",&(a.lname));
        scanf("%d",&(a.mat));
        if(fwrite(&a,sizeof(student),1,f)==1)
        {
             printf("successfully wrote");  // this message does get printed
        }
        return(1); // successfully found
    }

    printf("we didn't find what you searched for\n");
    return(0);
}

最佳答案

除了bluesawdust发的那个,我还发现了一些其他的代码错误:

  • //文件以“wb+”模式打开:这意味着您的文件在打开时被破坏(参见 here )。您可能想使用 "rb+"

  • 因为您没有初始化您的student s 结构(并且由于我之前的观点,没有记录被写入其中)s.mat 包含一个随机值

  • scanf("%d",&(a.mat));:对于printf,需要将格式字符串改为 "%f"(但实际上你应该使用字符串类型,将 float== 进行比较不是好的做法,因为四舍五入)

关于c - 为什么 fwrite 不覆盖我在 wb+ 中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977656/

相关文章:

c - 指向空指针的指针 C

c - 如何计算二进制数C中的最大块长度

c - 如何在数组中连续写入

c++ - 在 main() 之前可能需要做什么样的操作

c - 如何传入整数指针数组

c - Unix - Pipe、forks、execlp、dup2、c 程序

c++ - 将用位集转换的二进制数放入 vector 中

python - 为什么在 python3 中索引二进制字符串会返回整数?

c++ - 为什么 unsigned int 0xFFFFFFFF 等于 int -1?

c - GDB结构输出