使用 fwrite 修改二进制文件上的一个 int 时分配的随机值

Random values assigned when using fwrite to modify one int on a binary file

功能不起作用

我正在编写一个简单的函数来打开一个包含 20 个整数的文件。 用户可以 select 一个从 1 到 20 的数字,然后是分数。然后新的分数应该被写入文件,并且当访问文件时新的值应该在那里。

void EditScore(void)
{
    printf("\nThis is the function to edit a score.\n");
    FILE *fPtr = NULL;
    int student = 0;
    int score = 0;

    if((fPtr = fopen("score.dat", "rb+")) == NULL)
    {
        printf("File could not be opened.\n");
    }
    else
    {
        printf("Enter the number of student: ");
        scanf("%d", &student);
        printf("Enter the new score for the student: ");
        scanf("%d", &score);

        fseek(fPtr, (student * sizeof(int) - 1), 0);
        fwrite(&score, sizeof(int), 1, fPtr);
    }
    fclose(fPtr);
}

例如,选择学生 1 并给它一个新的分数 10,当与另一个函数一起使用以显示文件的编号时,应该得到 10 分。

如果我给10分,读取文件时的值为:167772160。 我一直在尝试查看我使用fwrite函数是否有错误,但我没有找到任何东西。

阅读功能(显然工作正常)

    void DisplayScore(void)
{
    printf("\nThis is the function to display the scores.\n");
    FILE *fPtr = NULL;
    int grades[20] = {0};

    if((fPtr = fopen("score.dat", "rb")) == NULL)
    {
        printf("File could not be opened.\n");
    }
    else
    {
        fread(&grades, sizeof(int), 20, fPtr);
        for(int i = 0; i < 20; i++)
        {
            printf("The score of student %d is %d\n", i + 1, grades[i]);
        }
    }

    fclose(fPtr);
}

也许我的错误是在再次读取文件值的过程中,所以我将包括显示这些值的函数,如果它有用的话。

我没有收到任何编译器错误或警告,而且我一直在查看其他工作示例,所以我真的不知道我做错了什么。

这一行

fseek(fPtr, (student * sizeof(int) - 1), 0);

应该是

fseek(fPtr, (student-1) * sizeof(int), 0);

否则写入移动一个字节。