c - How can I save a structure which contains allocated memory to file? -
// headers struct address{ int id; char *name; char *email; }; struct database{ struct address *rows; int max_size; int max_data; }; struct connection{ file *file; struct database *db; }; int main(int argc, char *argv[]){ int i; struct connection *conn; conn->file = fopen(argv[3], "w+"); conn->db->max_size = atoi(argv[1]); conn->db->max_data = atoi(argv[2]); conn->db->rows = malloc(sizeof(struct address) * (db->max_size)); for(i=0; i<db->max_size; i++){ struct address adr = {.id = i}; adr.name = malloc(conn->db->max_data); adr.email = malloc(conn->db->max_data); conn->db->rows[i] = addr; } /* other code(s) here * * */ }
now, according these snipped code, how can save conn->db structure conn->file contents? after that, must able read file, again.
i can't use stack type structure, because "max_data" , "max_size" typed user!
have looked writing binary file.
for writing
file *write_ptr; write_ptr = fopen("test.bin","wb"); // w write, b binary fwrite(conn->db,sizeof(conn->db),1,write_ptr); // write number of bytes determined structure size binary file
for reading file
file *read_ptr; read_ptr = fopen("test.bin","rb"); // r read, b binary fread(conn->db,sizeof(conn-db),1,ptr); // read bytes determined size of structure form file current conn->db structure
note binary files cant opened , read in paintext
wiki
Comments
Post a Comment