Writing a linked list to binary file(C)

余生长醉 提交于 2019-12-24 07:12:54

问题


So I have set up a linked list and read data from a file, done some calculation and manipulation and now I want to store the new list into a binary file.

Here is my struct setup:

typedef struct Comp{
    char name[5];
    char node1[5], node2[5];
    float value;    //value
}ComponentType;

typedef struct ListNodeT{

    ComponentType Component;
    float voltage, power, current;
    struct ListNodeT *nextPtr;
}ListNodeType;

In a separate function I am trying to write to a a file:

FILE *filePtr;

char fileName[13] = "SaveData.bin";
filePtr = fopen(fileName, "wb");
int index = 0;

while (CircuitData != NULL)
{
    fwrite(CircuitData, sizeof(ListNodeType), 1, filePtr);
    CircuitData = CircuitData->nextPtr;
    index++;
}

The above code is not working so now my question is, can I write to the file using a single fwrite(CircuitData, sizeof(ListNodeType), 1, filePtr) or should I write each component separately as follows:

fwrite(CircuitData->Component.name, sizeof(CircuitData->Component.name), 1, filePtr);

How should I be doing this? My second question is, how would I read this binary file again back into the Struct?


回答1:


Well, you won't be able to use the pointer-values from a file in a new invocation of the program, so you'll need to do something about that. You could make a copy before printing and zero-out the pointer; then when reading, you'll need to assign the correct pointer values for the newly allocated structs.

I'd probably read them with a recursive function. Something like this:

ListNodeType *read_list_from_file (FILE *fileptr) {
    ListNodeType node;
    ListNodeType *nodeptr;
    if (fread(&node, sizeof(node), 1, fileptr) == sizeof(node)) {
        nodeptr = malloc(sizeof(node));
        //TODO: handle malloc failure
        memcpy(nodeptr, &node, sizeof(node);
        nodeptr->nextPtr = read_list_from_file(fileptr);
        return nodeptr;
    } else {
        return NULL;
    }
}



回答2:


if you intend to transmit the file and allow it to be read in by another computer, you may have the problem with byte representation (f.e. the float values). One approach is, to convert the floats to a string representation on write() and convert it back on read().

Better would be to use a well defined format (like CSV or xml)



来源:https://stackoverflow.com/questions/19444803/writing-a-linked-list-to-binary-filec

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