IO进程线程Day1

编写一条学生链表,写一些能够像链表里边添加数据的函数

        实现:将链表中的所有内容保存到文件中去以及读取文件中的所有内容,加载到链表里面

主函数

int main(int argc, const char *argv[])
{
    node_p H=create_head();
    //选择读取或者写入模式
    printf(" r  or  w :");
    char mode;
    scanf("%c",&mode);
    //以追加的方式打开文件
    FILE *fp=fopen("./stu.txt","a+");
    if(NULL==fp){
        perror("open error");
        return -1;
    }
    if('w'==mode){
        Stu stu[3]={"zhangsan",20,"male",\
                "lisi",21,"male",\
                "wangwu",22,"female"};
        insert_head(H,stu[0]);
        insert_head(H,stu[1]);
        insert_head(H,stu[2]);
        node_p p=H->next;
        while(p!=NULL){
            fprintf(fp,"%s\n%d\n%s\n",p->data.name,p->data.age,p->data.sex);
            p=p->next;
        }
    }
    else if('r'==mode){
        while(1){
            node_p p=create_node();
            int res=fscanf(fp,"%s%d%s",p->data.name,&(p->data.age),p->data.sex);
            if(res<=0){
                free(p);
                break;
            }
            p->next=H->next;
            H->next=p;
            H->len++;
        }
        show_link(H);
    }
    fclose(fp);                                                                      
    return 0;
}

 结构体类型

//学生结构体
typedef struct stu
{
    char name[20];
    int age;
    char sex[10];
}Stu,*Stu_p;

//链表结构体
typedef struct node         
{
    union{
        Stu data;
        int len;
    };
    struct node *next;
}node,*node_p;

 链表的函数

node_p create_head(){
    node_p H=(node_p)malloc(sizeof(node));
    if(NULL==H){
        printf("创建失败\n");
        return NULL; 
    }
    H->next=NULL;
    H->len=0;
    return H;
}

node_p create_node(){
    node_p new=(node_p)malloc(sizeof(node));
    if(NULL==new){
        printf("创建失败\n");
        return NULL; 
    }
    new->next=NULL;
    return new;
}

//头插
int insert_head(node_p H,Stu data){
    if(NULL==H){
        printf("传入参数错误\n");
        return -1;
    }
    node_p new=create_node();
    if(NULL==new){
        printf("创建失败\n");
        return -1; 
    }
    new->data = data;
    new->next=H->next;
    H->next=new;
    H->len++;
    return 0;
}                                                                       

//遍历链表
void show_link(node_p H){
    if(NULL==H||H->len==0){
        printf("传参错误\n");
        return;
    }
    node_p p=H->next;
    while(p!=NULL){
        printf("%s\n%d\n%s\n",p->data.name,p->data.age,p->data.sex);
        p=p->next;
    }
}

运行结果

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值