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.
– Rafael Coelho
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.
– Kollins Lima