1
votes

I would able to read all my struct bytes by bytes (block of bytes are large "sizeof(Today)" so it's 8 bytes large). I attempt more and more times, but I can't! Give me help please!

Bin file: "temp.bin"

My struct:

typedef struct
{
    int year;
    int month; 
} Today;

And this is part of code that should be read 8 bytes each cycle:

 Today *d;
 d = malloc(sizeof(Today));

 fp = fopen("temp.bin", "rb"); 

 while(!feof(fp))
 { 
     fread(d, sizeof(Today), 1, fp);

     printf("Year = %i\n", d->year);
     printf("Month = %i\n", d->month);     
 } 

 fclose(fp);

More probably is wrong the while condition and fread() function, but I tried all possible combination but the output is never the right one! Thank you all

2
Call free after malloc. - cadaniluk
I call free, but never happens! And Yes, I have 2 duplicated value printed! - user3649959
Sidenote: Nothing wrong with malloc, but if you are allocating 1 Today temporarily, it would be more straightforward to just define it locally as Today d;. Then you don't have to deal with malloc/free hassle. Your structure is really small in size, so size shouldn't really be an issue. - user694733

2 Answers

0
votes

You may want to allocate space for all your blocks first e.g.

fp = fopen( "temp.bin", "rb" );
if ( fp != NULL )
{
   fseek( fp, 0L, SEEK_END );
   size_t size = ftell(fp);
   rewind(fp);

   Today *d;
   d = malloc(size);
   fread( d, sizeof(Today), size/sizeof(Today), fp );
   fclose(fp);
}

then you got the structs in an array

e.g. printf( "month: %d", d[5].month);

then do what you need to do on each element in the array then later write it back. Depends on how large your file is though

0
votes

there is nothing about your code, i guess your file format is not as you think.

i also wander why you have to allocate memory for struct.

the code here is similar to that you provided. it just demonstrate the writing of the data in the format you described and then retrieving it without any lose.

#include <stdio.h>
#include <string.h>
typedef struct
{
    int year;
    int month; 
} Today;

#define DataFile    "temp.bin"
int main(){
    Today d;
    printf("sizeof(Today)=%d\n",sizeof(Today));

    FILE  *fp = fopen(DataFile, "wb");
    for(int i=1;i<13;i++){
        d.month=i;
        d.year=2000+i;
         fwrite(&d, sizeof(Today), 1, fp);
    } 
    fclose(fp);

    printf("write complete, press a key to read\n");
    _getch();

    fp = fopen(DataFile, "rb"); 

    while(fread(&d, sizeof(Today), 1, fp)){ 
         printf("Year = %i\t", d.year);
         printf("Month = %i\n", d.month);     
    } 
    fclose(fp);
    return 0;
}