I have the following structure and I am trying to write/read it to/from a file.
struct block{
int id;
int row, col;
int alive;
struct block *next_up, *next_dn, *next_lt, *next_rt;
};
I have the following read and write functions, but they are returning the wrong address, possibly the address of the pointer, not the address pointed at. The pointers will either be NULL
or contain the memory address of a struct block
.
save:
void save_blocks(){
FILE *my_stream;
my_stream = fopen ("blocks.txt", "w");
int c;
for(c=0;c<blk_cnt;c++){
fprintf(my_stream, "%d ", the_blocks[c].id);
fprintf(my_stream, "%d ", the_blocks[c].row);
fprintf(my_stream, "%d ", the_blocks[c].col);
fprintf(my_stream, "%d ", the_blocks[c].alive);
fprintf(my_stream, "%p ", the_blocks[c].next_up);
fprintf(my_stream, "%p ", the_blocks[c].next_dn);
fprintf(my_stream, "%p ", the_blocks[c].next_lt);
fprintf(my_stream, "%p ", the_blocks[c].next_rt);
}
fflush (my_stream);
fclose (my_stream);
}
this is the load:
void load_blocks(){
blk_cnt = 0;
int id, row, col, alive;
struct block *next_up, *next_dn, *next_lt, *next_rt;
FILE *my_stream;
my_stream = fopen("blocks.txt", "r");
while(!feof(my_stream)){
int blk_cnt = fscanf(my_stream, "%d %d %d %d %p %p %p %p",
&col, &alive, &next_up, &next_dn, &next_lt, &next_rt);
the_blocks[blk_cnt].id = id;
the_blocks[blk_cnt].row = row;
the_blocks[blk_cnt].col = col;
the_blocks[blk_cnt].alive = alive;
the_blocks[blk_cnt].next_up = next_up;
the_blocks[blk_cnt].next_dn = next_dn;
the_blocks[blk_cnt].next_lt = next_lt;
the_blocks[blk_cnt].next_rt = next_rt;
blk_cnt++;
}
}
I tried using fwrite and fread but it was giving the wrong addresses for the pointers. I feel like I need to write &(*next_up)
but this seems wrong. I have searched and this question is similar, but not quite what I need. Finally, do I actually need the while(!feof())
loop? TIA.