stm32 从文件初始化链表
时间: 2023-07-10 13:11:35 浏览: 53
在STM32中,可以使用标准C库中的文件操作函数来读取文件中的数据,并将其存储到链表中。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
Node* initListFromFile(const char* filename) {
FILE* fp = fopen(filename, "r");
if (!fp) {
printf("Failed to open file: %s\n", filename);
return NULL;
}
Node *head = NULL, *tail = NULL;
int data;
while (fscanf(fp, "%d", &data) != EOF) {
Node* newNode = createNode(data);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
fclose(fp);
return head;
}
int main() {
Node* head = initListFromFile("data.txt");
// 遍历链表
Node* p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
在上面的代码中,我们定义了一个`Node`结构体来表示链表的节点,其中`data`成员表示节点存储的数据,`next`成员表示指向下一个节点的指针。我们还定义了`createNode()`函数来创建一个新的节点。`initListFromFile()`函数用于从文件中读取数据,并将其存储到链表中。该函数打开指定的文件,读取文件中的数据,并将每个数据项存储到一个新的节点中。如果链表为空,则将头指针和尾指针都指向新节点。否则,将新节点添加到链表的尾部,并更新尾指针。最后,函数返回链表的头指针。
在`main()`函数中,我们调用`initListFromFile()`函数来初始化链表。然后,我们遍历链表并打印每个节点的数据值。
需要注意的是,在使用链表时,需要特别注意内存管理。在这个示例中,我们使用`malloc()`函数为每个节点分配内存,并且在使用完成后需要使用`free()`函数释放节点的内存。