看你的链表在文件中是什么形式的存在了, 读取与写入的过程是一样的。struct node {
char data[DATASIZE];
struct node *next;
};
struct node *read_list_from_file(const char *filename)
{
struct node *pnode = NULL;
static struct node *head = pnode;
FILE *fp = fopen(filename, "r");
if (!fp)
return NULL;
while (!feof(fp)) {
if (pnode) {
pnode = pnode->next;
}
pnode = calloc(1, sizeof(struct node));
fread(pnode->data, 1, sizeof(pnode->data), fp);
}
fclose(fp);
return head;
}
void write_list_to_file(struct node *head, char filename)
{
struct node *tmp = head;
FILE *fp = fopen(filename, "w");
if (!fp)
return;
while (!tmp) {
fwrite(tmp->data, 1, sizeof(tmp->data), fp);
tmp = tmp->next;
}
fclose(fp);
}
追问
pnode = calloc(1, sizeof(struct node));
错误6error C2440: “=”: 无法从“void *”转换为“node *”c:\users\wxy\documents\visual studio 2013\projects\学生成绩管理\学生成绩管理\源.cpp1431学生成绩管理
这是什么问题呢?
追答
只是部分代码给个思路,后面要你自己去修改。#include
#include
#include
#define DATASIZE 10
struct node {
char data[DATASIZE];
struct node *next;
};
void read_list_from_file(char *filename, struct node **pphead)
{
struct node *pnode = NULL;
struct node *head = pnode;
FILE *fp = fopen(filename, "r");
if (!fp)
return;
while (!feof(fp)) {
if (pnode) {
pnode = pnode->next;
}
pnode = calloc(1, sizeof(struct node));
fread(pnode->data, 1, sizeof(pnode->data), fp);
}
fclose(fp);
*pphead = head;
}
void write_list_to_file(struct node *head, char *filename)
{
struct node *tmp = head;
FILE *fp = fopen(filename, "w");
if (!fp)
return;
while (!tmp) {
fwrite(tmp->data, 1, sizeof(tmp->data), fp);
tmp = tmp->next;
}
fclose(fp);
}
int main()
{
return 0;
}
温馨提示:答案为网友推荐,仅供参考