我没有正确使用 fseek() 吗?

Am I not using fseek() properly?

我正在尝试更新我的二进制文件中的一些信息,但我在尝试向后返回到行首时遇到问题。

void updateSalary(char* filename)
{
    int i = 0;
    employee temp;
    char c;
    float increase;
    FILE *fup = fopen(filename, "rb+");
    if (fup == NULL)
    {
        printf("Unable to read the file\n");
        return;
    }

    fread(&temp, sizeof(employee), 1, fup);
    while (!feof(fup))
    {
    printf("How big is the increase to %s's salary?\n", temp.name);
    scanf("%f", &increase);
    temp.salary += increase;
    fseek(fup, (i * sizeof(employee)), SEEK_SET);
    fwrite(&temp, sizeof(employee), 1, fup);
    fread(&temp, sizeof(employee), 1, fup);
    i++;
    }
fclose(fup);
}

问题是,例如,如果我选择更新 2 名员工,出于某种原因,while 循环不会在第 2 名员工处停止,函数继续运行。

提前致谢。

编辑: 似乎 fwrite();函数没有前进(按位置含义)到下一行,所以有固定代码:

void updateSalary(char* filename, float threshold)
{
    int i = 0;
    employee temp;
    char c;
    float increase;
    FILE *fup = fopen(filename, "r+b");
    if (fup == NULL)
    {
        printf("Unable to read the file\n");
        return;
    }
    //fread(&temp, sizeof(employee), 1, fup);
    while (fread(&temp, sizeof(employee), 1, fup))
    {
    printf("How big is the increase to %s's salary?\n", temp.name);
    rewind(stdin);
    scanf("%f", &increase);
    temp.salary += increase;
    fseek(fup, (i * sizeof(employee)), SEEK_SET);
    fwrite(&temp, sizeof(employee), 1, fup);
    **fseek(fup, ((i+1) * sizeof(employee)), SEEK_SET);**
    i++;
    }
fclose(fup);
}

您应该查看 fopen 文档中的细则:

In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file.

读取和写入可能会被缓冲,但仍共享一个文件位置。在不提醒运行时的情况下切换模式(使用 fseek)可能会弄乱缓冲。

所以行

fseek(fup, (i * sizeof(employee)), SEEK_SET);
fwrite(&temp, sizeof(employee), 1, fup);
fread(&temp, sizeof(employee), 1, fup);

写入和读取之间还需要 fseek