写链表二进制文件(C)的 [英] Writing a linked list to binary file(C)
问题描述
因此,我成立了一个链表,从文件中读取数据,做了一些计算和处理,现在我想将新列表存储到一个二进制文件。
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.
下面是我的结构设置:
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++;
}
以上code未工作,所以现在我的问题是,使用单一FWRITE(CircuitData,sizeof的(ListNodeType),1,filePtr)我可以写入文件,或者我应该分开来写每个组件,如下所示:
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?
推荐答案
那么,你将不能够在一个新的程序调用使用从文件指针值,所以你需要做的事情关于那个。你可以打印和零出指针之前进行复印;那么阅读时,你需要分配正确的指针值新分配的结构。
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;
}
}
这篇关于写链表二进制文件(C)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!