Here is a simpe program that stores struct into binary file
The struct and item in it
typedef struct Item
{
int busy; //item is busy
int key; //item key
int len; // len of info in item
int release; //item release (version of item)
char *info; //info (char array)
}Item;
typedef struct Table
{
Item* items[MAX];
int size = MAX;
}Table;
Here is the code that implements file read and write functionality
// Write table to file
void WriteToFile(const char *filename, Table* table)
{
FILE *fl;
Item *p;
fl = fopen(filename, "w+b");
fwrite(&(table->size), sizeof(int), 1, fl);
for (int i = 0; i < table->size; i++)
{
p = table->items[i];
if (p->busy != 0) //Write only elements with busy != 0
{
fwrite(&(p->key), sizeof(int), 1, fl);
fwrite(&(p->release), sizeof(int), 1, fl);
fwrite(&(p->len), sizeof(int), 1, fl);
fwrite(&(p->info), sizeof(char), p->len, fl); //p->len contains strlen(info)
}
}
fclose(fl);
}
// Read table from binary file
int ReadFromFile(const char *filename, Table* table)
{
FILE *fl;
char *info;
int key = NULL;
int release = NULL, len;
fl = fopen(filename, "r+b");
if (fread(&table->size, sizeof(int), 1, fl) != 1) return 0;
while (!feof(fl))
{
if (fread(&key, sizeof(int), 1, fl) != 1) return 1;
if (fread(&release, sizeof(int), 1, fl) != 1) return 0;
if (fread(&len, sizeof(int), 1, fl) != 1) return 0;
info = (char *)malloc(len);
if (fread(&info, sizeof(char), len, fl) != len) return 0;
//Code that inserts item to table
}
fclose(fl);
return 1;
}
If i try to look info variable under debugger when reading it from file I've got a message "Error reading characters of string". On exit from ReadFromFile function i'm getting an error "Stack around the variable 'info' was corrupted."