Home > Software design >  C - How to increment first int of a file
C - How to increment first int of a file

Time:11-15

I have a file where i want the first sizeof(int) bytes to store the number of elements following in the file. I would like to increment this value whenever i add an element to the file.

The code looks like this:

int main() {
    int val = 3;

    FILE *file = fopen("hey", "wb");
    fwrite(&val, sizeof(int), 1, file);
    fclose(file);

    increment_val();
}

void increment_val() {
    int val;
    
    FILE *file = fopen("hey", "ab ");
    fread(&val, sizeof(int), 1, file);

    val  ;

    fseek(file, 0, SEEK_SET);
    fwrite(&val, sizeof(int), 1, file);

    fseek(file, 0, SEEK_SET);
    fread(&val, sizeof(int), 1, file);

    printf("%d", val);

    fclose(file);
}

I initialy write an int with the value 3 to the file.
I then read this value, increment it and write it back.
However when reading the value after this it still holds the original value of 3 instead of 4.

CodePudding user response:

Interesting problem (thanks - good puzzle for the morning as I wasn't aware of this). But the underlying issue is that when you open for append, the writes ignore seeking. Thus the code in increment_val should be:

FILE *file = fopen("hey", "rb ");

Note that you don't need the b really. You might be coming from python where that is signalling binary?

  • Related