Problems with fwrite in binary file

Asked

Viewed 495 times

2

I am trying to write and read an integer in binary file with the following code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct{
    int free_slot;
}header;

void main(void){
    FILE *fd = fopen("test.dad","a+b");
    fseek(fd,0,SEEK_SET);

    header aux_header;

    fread(&aux_header, sizeof(header),1,fd);
    printf("Header: %d\n", aux_header.free_slot);
    scanf("%d",&aux_header.free_slot);

    fseek(fd,0,SEEK_SET);
    if(fwrite(&aux_header,sizeof(header),1,fd) != 1)
        puts("Write Error");

    fclose(fd);
}

I am running this program several times, but after the first writing, the next ones are ignored and do not go to the file.

  • In C, until you flush the file or close it, what is stored in the buffer is not passed to the actual file. I advise you to open the file for reading, use it and close it. And when you want to write in it, do the same procedure.

  • Even though it didn’t work, I tried to open (a+b)->write->close->open for reading (Rb)->read->close, but the problem continues, after successfully writing the first number, the others don’t overwrite it.

2 answers

2

In C, until you flush the file or close it, what is stored in the buffer is not passed to the actual file. I advise you to open the file for reading, use it and close it. And when you want to write in it, do the same procedure.

Follow the code I used for testing:

typedef struct{
    int free_slot;
}header;

int main(){
    FILE *fd = fopen("test.bin","ab");
    header aux_header;

    scanf("%d",&aux_header.free_slot);
    fwrite(&aux_header,sizeof(header),1,fd);
    aux_header.free_slot = 2; 
    fwrite(&aux_header,sizeof(header),1,fd);
    fclose(fd); 

    fd = fopen("test.bin","rb");
    rewind(fd); 
    while (!feof(fd)) { 
        fread(&aux_header, sizeof(header),1,fd); 
        printf("Header: %d\n", aux_header.free_slot); 
    }
    fclose(fd); 
    return 0;
}
  • Thanks for the answer, Rafael, but it’s not what I’m looking for yet. What I want is to overwrite the first position. I don’t know why, but I tried to use Rewind before writing (using your code) but always writing occurs at the end, because?

  • Now I see what you want. You can use the fseek function to move that you were not using and the ftell function to find the current position (it returns a long and this long can be used as fseek function input parameter).

  • The problem is that even using fseek to return (and checking with ftell that I’m at the beginning of the file), the writing occurs at the end of the file when I give fwrite. I’m not able to overwrite the first positions of the file.

1


I found a solution to the problem. Using the r+b mode the algorithm works (I was using a+b to create a file if it didn’t exist, but for some reason this mode isn’t working in my application).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.