标题:单链表写入文件
只看楼主
Gavinzhz
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2013-3-26
 问题点数:0 回复次数:0 
单链表写入文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
    int sno;
    char name[128];
}TYPE;
typedef struct student
{
    TYPE data;
    struct student *next;
}STU;
static FILE *fp;
void add();
void visit();
void destroy(STU *);
int main()
{
    while(1)
    {
        printf("============================\n");
        add();
        printf("=============================\n");
        visit();
    }
    fclose(fp);
    return 0;
}
void add()
{
    fp=fopen("stu.txt","a+");
    char ch;

    if((ch=fgetc(fp))==EOF)
    {
        STU *st=(STU *)malloc(sizeof(STU));
        printf("请输入学号!\n");
        scanf("%d",&st->data.sno);
        printf("请输入姓名!\n");
        scanf("%s",st->data.name);
        st->next=NULL;
        fwrite(st,sizeof(STU),1,fp);
        free(st);
    }
    else
    {
        STU *head;
        rewind(fp);
        fread(head,sizeof(STU),1,fp);
   
        //获取尾节点
        STU *last=head;
        for(;last->next != NULL;)
            last=last->next;
   
        //新节点的添加
        STU *st=(STU *)malloc(sizeof(STU));
        printf("请输入学号!\n");
        scanf("%d",&st->data.sno);
        printf("请输入姓名!\n");
        scanf("%s",st->data.name);
        last->next=st;
        st->next=NULL;
        fwrite(st,sizeof(STU),1,fp);
        free(st);
    }
}
void visit()
{
    fp=fopen("stu.txt","r");
    if(fp==NULL)
    {
        printf("error!\n");
        exit(1);
    }
    STU *head;
    rewind(fp);
    fread(head,sizeof(STU),1,fp);
    if(head!= NULL)
        for(;head != NULL;head=head->next)
            printf("学号:%d   姓名:%s\n",head->data.sno,head->data.name);
    else
        printf("数据库数据为空!\n");
}
请各位大大帮忙看一下,为什么链表的数据写不进文件,谢谢了!
搜索更多相关主题的帖子: void static include return visit 
2013-04-07 18:29



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-403246-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.040276 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved