Search code examples
cfwritefread

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


Function that it's not working

I'm writing a simple function that opens a file containing 20 ints. The user can select a number from 1 to 20 and then a score. Then the new score should be written onto the file, and when accessing the file the new value should be there.

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);
}

For example, choosing Student 1 and giving it a new score of 10 should give a score of 10 when used with another function to display the numbers of the file.

If I give the score of 10, the value when reading the file is: 167772160. I've been trying to see if there's an error on my use of the fwrite function, but I haven't found anything.

Reading function (apparently working fine)

    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);
}

Maybe my error is on the process of reading the values of the file again, so I'm going to include the function that displays those values as well if it's useful.

I don't get any compiler error nor warning and I've been looking at other working examples, so I really don't know what I'm doing wrong.


Solution

  • This line

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

    should be

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

    otherwise the writing is shifted one byte.