C文件读写

本文展示了如何使用C语言进行链表数据的读写操作。通过定义结构体NodeData和链表节点结构体node_t,实现了创建链表、将链表数据写入文件以及从文件读取数据回链表的功能。示例代码中包含`writeData2File`和`read2LinkedList`两个函数,用于文件的读写操作。

//读写文件

#include <stdio.h>

#include <stdlib.h>

 

typedef struct

{

int value;

} NodeData;

 

typedef struct N

{

NodeData data;

struct N *next;

} node_t;

 

void writeData2File(node_t *linkedlist, FILE *fp)

{

while (linkedlist != NULL)

{

fwrite(&(linkedlist->data), sizeof(NodeData), 1, fp);

linkedlist = linkedlist->next;

}

}

 

void maintainList(node_t **head, node_t **pre, node_t **current)

{

if (*head == NULL)

{

*head = *current;

*pre = *head;

}

else

{

(*pre)->next = *current;

*pre = *current;

}

(*pre)->next = NULL;

}

 

node_t *createLinkedList()

{

char cmd;

node_t *head = NULL;

node_t *pre = NULL;

while (1)

{

printf("Input data? Y for yes, N for no:");

scanf("%c", &cmd);

fflush(stdin);

if (cmd == 'Y')

{

node_t *new = malloc(sizeof(node_t));

printf("data value:");

scanf("%d", &new->data.value);

fflush(stdin);

maintainList(&head, &pre, &new);

}

else

break;

}

return head;

}

 

node_t *read2LinkedList(FILE *fp)

{

node_t *head = NULL;

node_t *pre = NULL;

while (1)

{

node_t *current = malloc(sizeof(node_t));

if (fread(&current->data, sizeof(NodeData), 1, fp) == 1)

maintainList(&head, &pre, &current);

else

{

free(current);

break;

}

}

return head;

}

 

int main()

{

FILE *fp = fopen("newfile.txt", "w+");

 

//创建链表

node_t *headOfList = createLinkedList();

//将链表数据写入文件

writeData2File(headOfList, fp);

 

//回到文件开头位置

rewind(fp);

 

//从文件读数据到链表

node_t *head = read2LinkedList(fp);

 

//从头节点开始显示数据

while (head != NULL)

{

printf("value: %d\n", head->data.value);

head = head->next;

}

 

fclose(fp);

return 0;

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值