[英]Binary Saving a Struct with Struct array members (C)?
I'm currently working on a program that uses these two structs: 我目前正在开发一个使用这两个结构的程序:
//Struct to hold contact info about a friend
typedef struct
{
char *firstName, *lastName;
char *home, *cell;
} Friend;
//Struct to hold a list of friends and keep track of its size.
typedef struct
{
Friend *listEntries;
size_t listSize;
} FriendList;
Each of the string members within the Friend
struct is dynamically allocated, as is the listEntries
array inside FriendList
. 每个内的线部件的Friend
结构是动态分配的,因为是listEntries
内部阵列FriendList
。 I'm trying to save a FriendList
as a binary record, but when I try to do this using fwrite()
and then read it back with fread()
, the listEntries
array of the FriendList
that is read from the file is empty. 我想保存FriendList
为二进制记录,但是当我试图做到这一点使用fwrite()
然后用读回fread()
该listEntries
的阵列FriendList
是从文件中读取是空的。 Is there any way to save a dynamic struct like this? 有没有办法保存像这样的动态结构?
EDIT: The functions I use to read/write the struct are: 编辑:我用来读/写结构的函数是:
void writeList(FriendList *fl, char* filename)
{
FILE *fp = fopen(filename, "wb+");
if(fp != NULL)
{
fwrite(fl, sizeof(FriendList), 1, fp);
}
fclose(fp);
}
void readList(FriendList *dest, char* filename)
{
FILE *fp = fopen(filename, "rb");
if(fp == NULL)
{
printf("oops...");
}
else
{
fread(dest, sizeof(FriendList), 1, fp);
}
close(fp);
}
You must save the data the pointers point at, not the pointers themselves. 您必须保存指针指向的数据,而不是指针本身。 Pointers are meaningless outside your process as it exists at the very moment, so saving a pointer value to disk means nothing. 指针在你的进程之外是没有意义的,因为它现在存在,因此将指针值保存到磁盘意味着什么。
In general, you cannot do this by using a single fwrite()
to dump out a structure, since that will not follow the pointers. 通常,您不能通过使用单个fwrite()
来转储结构,因为它不会遵循指针。
You need to invent an actual external file format to use, and write code to save and load it. 您需要创建一个实际的外部文件格式来使用,并编写代码来保存和加载它。 I would suggest a text-based format, since most of your data is text. 我建议使用基于文本的格式,因为大多数数据都是文本。 Perhaps CSV ? 也许CSV ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.