Problems with fwrite in binary file

2

I'm trying to write and read an integer in a 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'm running this program several times, but after the first write, the next ones are skipped and do not go to the file.

    
asked by anonymous 30.10.2017 / 17:06

2 answers

1

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

    
02.11.2017 / 18:50
2

In C, as long as you do not flush the file or close it, what is stored in the buffer is not passed to the fact 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.

Here is 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;
}
    
31.10.2017 / 01:35