Search code examples
cbinaryfilesfwrite

Change a value in a binary file (C)


The program should change a specific value in a record, and I used fseek and fwrite to do so. But when I run it, it overwrites the next record.

Here's a part of my program :

j = 0;
while ((fread(&Rec, sizeof(Rec), 1, file) == 1) && (Found == 0))
{
    if (strcmp(Rec.Name, SearchName) == 0)
    {
        if (Rec.BD == SearchBD)
        {
            Found = 1;
            printf("\nEnter the new value : ");
            scanf("%f", &Val);

            fseek(file, (sizeof(Rec))*j, SEEK_SET);
            strcpy(Rec.Name, SearchName);
            Rec.BD = SearchBD;
            Rec.V = Val;
            fwrite(&Rec, sizeof(Rec), 1, file);

        }

    }

    j++;
}

Solution

  • Your code cannot overwrite the next record. The code is correct. However, if you use Rec further on in your program (you gave only a snippet), then you will find that Rec has unexpected values. That is because after the record searched for was found, the while loop performs one more fread before exiting the loop. That is because the while loop must be written as:

    while ((Found == 0) && (fread(&Rec, sizeof(Rec), 1, file) == 1))
    

    as otherwise another fread will be performed before found will be tested and the loop exited.