作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
// 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
*
*
*/
}
现在,根据这些代码片段,如何将 conn->db 结构保存到 conn->file 中并包含所有内容?之后,我必须能够再次从文件中读取它。
我无法使用堆栈类型结构,因为“max_data”和“max_size”是用户输入的!
最佳答案
您是否考虑过写入二进制文件。
用于写作
FILE *write_ptr;
write_ptr = fopen("test.bin","wb"); // w for write, b for binary
fwrite(conn->db,sizeof(conn->db),1,write_ptr); // write number of bytes determined by the structure size into a binary file
用于读取该文件
FILE *read_ptr;
read_ptr = fopen("test.bin","rb"); // r for read, b for binary
fread(conn->db,sizeof(conn-db),1,ptr); // read bytes determined by size of structure form the file into the current conn->db structure
请注意,二进制文件无法在painttext中打开和读取
关于c - 如何将包含已分配内存的结构保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852584/
我是一名优秀的程序员,十分优秀!