I/O作业1

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct stu
{
	char name[50];
	int age;
	char sex[20];
}stu,*stu_p;

typedef struct link
{
	union{
		stu data;
		int len;
	};
	struct link *next;
}node,*node_p;

node_p creat_link()
{
	node_p L = (node_p)malloc(sizeof(node));
	if(L==NULL)
	{
		printf("传参失败!\n");
		return NULL;
	}
	L->next=NULL;
	L->len=0;

	return L;
}
node_p creat_node(node_p L,stu data)
{
	node_p P = (node_p)malloc(sizeof(node));
	if(P==NULL)
	{
		printf("传参失败!\n");
		return NULL;
	}
	P->next=NULL;
	P->data=data;

	return P;
}

void head_insert(node_p L,stu data)
{
	if(L==NULL)
	{
		printf("传参失败!\n");
		return ;
	}
	node_p p = creat_node(L,data);
	p->next=L->next;
	L->next=p;
}

void show_link(node_p L)
{	
	node_p p = L->next;
	while(p!=NULL)
	{
		printf("%s %d %s\n",p->data.name,p->data.age,p->data.sex);
		p=p->next;
	}
}

/****************************主函数**********************************/
int main(int argc, const char *argv[])
{
	node_p L = creat_link();


	node_p p=L->next;

	char mod;
	printf("R?/W?:");
	scanf("%c",&mod);


	if(mod=='W')
	{	
		stu data1={"小赵",20,"m"}; 
		stu data2={"小李",18,"m"}; 
		stu data3={"小张",19,"w"}; 
		stu data4={"小徐",17,"w"}; 
		stu data5={"小陈",21,"m"}; 

		stu Stu[50]={data1,data2,data3,data4,data5};
		for(int i=0;i<5;i++)
		{
			head_insert(L,Stu[i]);
		}


		FILE* fp = fopen(argv[1],"w");

		while(1)
		{
			fprintf(fp,"%s\n%d\n%s\n",p->data.name,p->data.age,p->data.sex);
			p=p->next;
			if(p==NULL){break;}
		}
		fclose(fp);
	}


	else if(mod=='R')
	{
		FILE *fp = fopen(argv[1],"r");
		if(fp==NULL)
		{
			printf("未找到该文件,无法读取!\n");
			return -1;
		}
		while(1){	
			node_p new = (node_p)malloc(sizeof(node));	
			if( fscanf(fp,"%s\n%d\n%s\n",new->data.name,&(new->data.age),new->data.sex)==EOF)
			{break;}     
			new->next=L->next;
			L->next=new;
			new=new->next;

		}
		show_link(L);
		fclose(fp);
	}
	else
		printf("无法识别该模式!\n");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值