0

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. 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. 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);
}
2
  • 1
    Please provide the code that does the fread/fwrite. Commented Nov 14, 2012 at 16:28
  • Oops, dunno why I didn't do that at first DX. Edited. Commented Nov 14, 2012 at 16:49

1 Answer 1

2

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.

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Oh okay, that makes sense. I went back and changed the program to use a CSV-ish format for the file and it works perfectly. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.