gpt4 book ai didi

c - 如何将包含已分配内存的结构保存到文件?

转载 作者:行者123 更新时间:2023-11-30 19:33:21 26 4
gpt4 key购买 nike

// 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 中并包含所有内容?之后,我必须能够再次从文件中读取它。

我无法使用堆栈类型结构,因为“ma​​x_data”和“ma​​x_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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com