Search code examples
cstreamfwritefread

Problems with fread and fwrite


I'm having some problems with a program that uses fwrite and fread -> fread (void*, size_t, size_t, FILE*);, when a set second size_t as any number different than zero it doesn't works. Here is the code; it doesn't works this way, if anyone could help I would appreciate.

P.S.: if I substitute that sc's on the read and write function it works, but not as expected.

#include<stdio.h>
#include<stdlib.h>
#define TAM 10
#define sc 5

typedef struct str_score{
    float scr;
    char nome[TAM];
}score;

int main(){

    FILE *arq;
    int x;
    score a[sc], i={0.00,"-empty-"};

    if ((fopen("highscore.bin", "wb+"))==NULL){
        perror("Erro na abertura do arquivo\n");
        return 1;
    }

    fwrite(&i,sizeof(score), sc, arq);

    fread(a ,sizeof(score), sc, arq);

    for (x=0;x<sc;x++){
        printf("%s %.2f", a[x].nome,a[x].scr);
    }

    return 0;

}

Solution

    1. Since i is not an array, the following line is not correct

      fwrite(&i,sizeof(score), sc, arq);
      

      This should be

      fwrite(&i,sizeof(score), 1, arq);
      

      You can write sc number of elements, only when you have an initialized array of size sc or more.

    2. You are not accepting the return value of fopen. Change your fopen line to

      if ((arq = fopen("highscore.bin", "wb+"))==NULL){
      
    3. Between the fwrite and fread, put a

      fseek(arq, 0, SEEK_SET);
      

    This resets the file pointer to beginning of the file where you started writing.