fread'ing and fwrite'ing a structure that contains pointers [duplicate]

前提是你 提交于 2019-12-02 10:28:01

You seem to have answered your own question, fread and fwrite just look at what's in memory and put that in the file. This works great if you're writing things that don't have pointers (e.g. big arrays of numbers). It's not designed to write structs with pointers.

If this file has a format, you need to do what the format says. If you're making up a format as you go, then you should write each member one by one into the file. You will need some sort of buffer to read into (you may need to resize this if you don't have a maximum length specification). Also, your database_write function will need to be changed quite a bit as well.

If device and resource can have variable length you should write down the size of device and then the data. Do the same for resource. When you read them back you can read the size, then allocate memory and finally read the value.

Manik Sidana

You have yourself described you problem. fwrite will write the address and not the value.

May be you can use a field for the length of device and resource in your structure "struct data". Create a wrapper for fread() and fwrite() which reads/writes this length. In this wrapper you can memcpy devices, resource in a temporary buffer and use fwrite() on it.

This is a simple and very basic solution.

While sending packets in networks, you will generally see a structures containing char pointers. The first 4/8 bytes store the length of the data and the remaining bytes contain the actual data. User reading the packet, first reads the beginning 4/8 bytes. Depending on this, read() call is issued to read the remaining data.

You may refer Is the "struct hack" technically undefined behavior?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!