Luis Poveda Luis Poveda - 1 month ago 11
C Question

C - Reading from binary file into any struct

I've been looking a lot but couldn't find any answer to my problem.

I'm building my own list library on C. My idea is to work with all posible type of data so I'm using void pointers.

First of all, this is my List.

File - node.h

struct Node{
void *data;
Node *next;
};


I have created some random structures for testing my methods such as add, delete, write, and more and are working fine.

File - test.cpp

struct telfList{
int telf;
char name;
};
struct calendar{
char month[5];
};


Here is where I write the struct to file.

bool saveToFile(struct Node *list, char *fileName){
FILE *file = fopen(fileName, "wb");
if(file == NULL){
return false;
}
struct Node *aux = list;
while(aux != NULL){
fwrite(&(aux->data), 1, sizeof(aux->data), file);
aux = aux->next;
}
fclose(file);
return true;
}


My problem comes here.
I want to read that file again and store the info back to the list and it has to work with every type of structs because in this test there are telfList and calendar but maybe in the future are enemies, players or whatever.
I don't know how to pass the type of data to the function by param or how to pass the fread by void pointer.

I know that function is wrong, is how I have it now, I proved all I know, I've read like hundred Questions here en stackoverflow but no one has this doubt/problem

In this example I'm trying to read the file and fill the telfList's struct with the data.

bool loadFromFile(struct Node **list, void* data, char *fileName){
FILE *file = fopen(fileName, "rb");
struct Node *aux = *list;
if(file == NULL){
return false;
}
data = fread(fileName, sizeof(*data), 1, file);
createNewList(list, data);
fclose(file);
return true;
}


This is how I create the list.

void createNewList(struct Node **list, void* data){
(*list) = createNode(data);
}
struct Node* createNode(void* data){
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}


I tried to explain it in detail but if need more code parts just say me.
Thank you.

EDIT: Thx to everyone for answering, I've been researching about serialization and your tips were very helpfull.

Answer

Serialization structs into the binary (or any other form) is a separate task for a separate library. Don't mix it with your List library.

For serialization I suggest to use some 3rd party library like protobuf-c. Even if you cannot use it in your project check it to understand the basic concepts of data serialization.