将链表保存在文件中 C语言

#include
#include
int count = 0;
typedef struct LinkList {
	int val;
	char name[20];
	struct LinkList* next;
} LinkList;
LinkList* create_LinkList() {
	LinkList* head = (LinkList*)malloc(sizeof(LinkList)), *p;
	p = head;
	int data = 0;
	while (data != 999) {
		LinkList* newnode = (LinkList*)malloc(sizeof(LinkList));
		printf("\n请输入新节点的值:\n(输入999以停止链表的建立!)\n");
		scanf("%d", &data);
		printf("请输入新节点的名字:\n");
		scanf("%s", newnode->name);
		newnode->val = data;
		p->next = newnode;
		p = newnode;
		p->next = NULL;
		count++;
	}
	return head;
}
void save(LinkList* head) {
	FILE* pf = fopen("linklist.txt", "wb");
	if (pf == NULL) {
		printf("打开文件失败!\n");
		return;
	}
	LinkList* p = head->next;
	while (p->next != NULL) {
		fprintf(pf, "%d%s", p->val, p->name);
		fprintf(pf, "%s", "\n");      //换行一定要加!
		p = p->next;
	}
	fclose(pf);
	pf = NULL;
	return;
}
void show(LinkList* head) {
	FILE* pf = fopen("linklist.txt", "rb");
	if (pf == NULL) {
		printf("打开文件失败!\n");
		return;
	}
	LinkList a[100];
	for (int i = 0; i < count - 1; i++) {
		fscanf(pf, "%d%s", &a[i].val, a[i].name);
		printf("%d %s-> ", a[i].val, a[i].name);
	}
	fclose(pf);
	printf("NULL");
	return;
}
void print_LinkList(LinkList* head) {
	if (head->next == NULL)
		return;
	LinkList* p = head->next;
	while (p->next != NULL) {
		printf("%d、%s-> ", p->val, p->name);
		p = p->next;
	}
	printf("NULL");
	return;
}
int main() {
	LinkList* head = (LinkList*)malloc(sizeof(LinkList));
	head->next = NULL;
	printf("开始创建链表!\n");
	head = create_LinkList();
	//print_LinkList(head);
	save(head);
	show(head);
	return 0;
}

你可能感兴趣的:(链表,c语言,数据结构)