//讀寫文件
#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(¤t->data, sizeof(NodeData), 1, fp) == 1)
maintainList(&head, &pre, ¤t);
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;
}