主题:怎样从文件中读取链表
wind_x
[专家分:0] 发布于 2011-04-05 20:12:00
请教一下怎样从文件中读取链表 ··我已经把链表存入了2进制文件中 可不知道怎么读取它 想直接fread(h,sizeof(struct guke),1,fp),直接读取头指针 然后用个struct guke *p指向头指针 来读取链表 可是这样不行 ··谁能帮帮我 我想要直接看下从文件中读取链表的代码
回复列表 (共3个回复)
沙发
fragileeye [专家分:1990] 发布于 2011-04-06 14:40:00
应该可以读结构的,链表也是一种结构。
可以先读结构,再取结构中的指针和数据即可。不过读的时候得控制长度。
[code=c]
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Link
{
DataType ele;
struct Link *next;
}*MyLink;
MyLink Init_Link(void);
void WriteInto(MyLink ,FILE *);
void ReadFrom (MyLink ,FILE *);
int main(int argc, char *argv[])
{
FILE *fp;
MyLink head;
char name[20];
puts("input the name of the file:");
gets(name); //注意长度即可
if((fp = fopen(name, "a+b")) == NULL)
{
fprintf(stderr, "Can't open the file \"%s\"", name);
exit(EXIT_FAILURE);
}
head = Init_Link(); //初始化
WriteInto(head, fp); //写
if((fp = fopen(name, "a+b")) == NULL)
{
fprintf(stderr, "Can't open the file \"%s\"", name);
exit(EXIT_FAILURE);
}
ReadFrom(head ,fp); //读
free(head);
return 0;
}
MyLink Init_Link(void)
{
MyLink head, p, q;
DataType x;
int count = 0;
p = head = (MyLink )malloc(sizeof(struct Link));
q = (MyLink )malloc(sizeof(struct Link));
puts("input the data of the linklist:");
while(scanf("%d", &x) == 1 && x > 0) //很懒lz理解。输入0或负数吧
{
count++; //头结点的ele用于记录数据长度
q->ele = x;
p->next = q;
p = q;
q = (MyLink )malloc(sizeof(struct Link));
}
p->next = NULL;
head->ele = count;
return head;
}
void WriteInto(MyLink head, FILE *fp)
{
MyLink p = head->next;
while(p != NULL)
{
fwrite(p, sizeof(struct Link), 1, fp);
p = p->next;
}
fclose(fp);
}
void ReadFrom(MyLink head, FILE *fp)
{
MyLink q = (MyLink )malloc(sizeof(struct Link));
int index = 0;
while(index < head->ele)
{
fread(q, sizeof(struct Link), 1, fp);
index++;
printf("loc = %p -- ele = %d\n",q->next ,q->ele);//q和q->next都行,反正是验证
}
free(q);
}[/code]
写的很粗糙,文件那块我也没学好,主要是验证下、、
板凳
wind_x [专家分:0] 发布于 2011-04-06 14:48:00
先谢过了哈··还没开看得 昨天晚上想了一晚上···都没搞定 希望能行[em2]
3 楼
cchmhao2010 [专家分:10] 发布于 2011-04-27 18:02:00
[url=http://www.worldgodshop.com/]Supra Shoes[/url] [url=http://www.worldgodshop.com/]Radii shoes[/url] [url=http://www.worldgodshop.com/]Prada Shoes[/url] [url=http://www.worldgodshop.com/]Jordan shoes[/url] [url=http://www.worldgodshop.com/]Christian Louboutin shoes[/url]
http://www.worldgodshop.com/
我来回复