I have a lot of data stored in bin format, as a sequence of structures. I want to be able to randomly read any of the structures and modify it in C. I try with the following code, but it does not work. Can someone fix this for me please?
In addition, will it be possible to remove the intermediate structure from the file between them?
Code below:
#include <stdio.h> #include <stdlib.h> struct rec { int x,y,z; }; void f_rite() { int i; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("test.bin","w"); for ( i=0; i < 5; i++ ) { my_record.x = i; fwrite( &my_record, sizeof(struct rec), 1, ptr_myfile ); } fclose(ptr_myfile); return; } void f_read() { int i; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("test.bin","r"); for ( i=1; i <= 5; i++) { fread(&my_record,sizeof(struct rec),1,ptr_myfile); printf("%d\n",my_record.x); } printf("\n"); fclose(ptr_myfile); return; } void f_rerite() { int i; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("test.bin","rw"); for ( i=5; i >= 0; i-- ) { fseek( ptr_myfile, sizeof(struct rec)*i, SEEK_SET ); fread( &my_record, sizeof(struct rec), 1, ptr_myfile ); my_record.x = my_record.x + 100; fwrite( &my_record, sizeof(struct rec), 1, ptr_myfile ); } fclose(ptr_myfile); return; } int main() { f_rite(); f_read(); f_rerite(); f_read(); return 0; }
source share