0

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;

}
user93353
  • 13,733
  • 8
  • 60
  • 122
user2536075
  • 3
  • 1
  • 2
  • 2
    It's just that your compiler punishes you for the formatting of your code by emitting buggy machine code. –  Jun 30 '13 at 08:16
  • 2
    (Seriously, format/indent your code and check the return value of `fread()` and `fwrite()`.) –  Jun 30 '13 at 08:16

1 Answers1

2
  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.

user93353
  • 13,733
  • 8
  • 60
  • 122
  • Thank's for the comment, it works now. About the "fwrite(&i,sizeof(score), sc, arq);", I tought that would write i for sc times. I substituted that for this - for(x=0;x – user2536075 Jun 30 '13 at 18:25
  • `I tought that would write i for sc times.` - it actually reads starting from `&i` for `sc * sizeof(i)` bytes - which is why your `fread` which does a similar thing works fine. – user93353 Jun 30 '13 at 19:42