Change .bin file data in C

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; } 
+3
source share
2 answers

Fopen lacks the "rw" flag. To read and write (update) you need "r +". Since this is binary data, you should use "r + b" and "wb" in your f_rite function and "rb" in your f_read function. Also:

  • Check the return value of calls that may fail, you will find that, for example, Error fwrite.
  • The f_rerite functions are repeated through 6 elements, you are disabled by one.
  • Your f_rerite also writes the next element. You probably want to update the current record as soon as possible. This means that you need fseek again after calling fread.
+3
source

"rw" is incorrect. Use "r+" . Remember to search after reading.

+2
source

Source: https://habr.com/ru/post/1484669/


All Articles