c语言读取txt存入链表,各位大神能否说下C语言如何在程序开始时候将文件内容读取到链表中呢...

#include 

#include 

typedef struct student

{

int id;

char name[32];

struct student* next;

}ST;

ST* create(ST* h)//头插创建链表;

{

ST* head = h;

ST* p =(ST*)malloc(sizeof(ST));

printf("请输入学号、姓名\n");

scanf("%d %s",&p->id,p->name);

if(head = NULL)

{

head = p;

p->next = NULL;

}

else

{

p->next = h;

head = p;

}

return head;

}

void write(ST* h)

{

ST* p= h;

FILE* fp=NULL;

fp = fopen("1.txt","w");

if(fp!=NULL)

{

printf("打开成功\n");

}

for(;p!=NULL;p=p->next)

{

fprintf(fp,"%d %s\n",p->id,p->name);

}

fclose(fp);

}

void print(ST* h)

{

ST* p = h;

printf("学号\t 姓名\t\n");

while(p!=NULL)

{

printf("%d\t %s\t\n",p->id,p->name);

p = p->next;

}

}

int main()

{

ST* head = NULL;

//head=read(head);

int n = 0;

printf("请输入要创建学生信息的个数\n");

scanf("%d",&n);

for(int i = 0;i

{

printf("请输入第%d个学生的信息\n",i+1);

head = create(head);

}

print(head);

write(head);

}

能否告知下,多谢啦!

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链表存入文件需要进行序列化操作,即将链表的数据转化为二进制数据流,然后写入文件读取文件的数据则需要进行反序列化操作,即将文件的二进制数据流转化为链表的数据。 下面是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node { char data[50]; struct node* next; } Node; void add(Node** head, char* data) { Node* new_node = (Node*)malloc(sizeof(Node)); strcpy(new_node->data, data); new_node->next = NULL; if (*head == NULL) { *head = new_node; } else { Node* cur = *head; while (cur->next != NULL) { cur = cur->next; } cur->next = new_node; } } void serialize(Node* head, char* filename) { FILE* file = fopen(filename, "wb"); Node* cur = head; while (cur != NULL) { fwrite(cur->data, sizeof(char), strlen(cur->data) + 1, file); cur = cur->next; } fclose(file); } Node* deserialize(char* filename) { FILE* file = fopen(filename, "rb"); Node* head = NULL; char data[50]; while (fread(data, sizeof(char), 50, file) != 0) { add(&head, data); } fclose(file); return head; } int main() { Node* head = NULL; add(&head, "hello"); add(&head, "world"); serialize(head, "data.bin"); Node* new_head = deserialize("data.bin"); Node* cur = new_head; while (cur != NULL) { printf("%s ", cur->data); cur = cur->next; } printf("\n"); return 0; } ``` 代码,`add`函数用于向链表添加节点,`serialize`函数用于将链表序列化到文件,`deserialize`函数用于从文件反序列化出链表。 在序列化时,我们使用了`fwrite`函数将字符串数据写入文件。 在反序列化时,我们使用了`fread`函数从文件读取字符串数据,并调用`add`函数将其添加到链表。 需要注意的是,在序列化和反序列化时,我们需要使用二进制文件模式(`"wb"`和`"rb"`),以确保在写入和读取数据时,不会将文本的换行符等字符转换为其他字符,从而导致数据失真。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值