#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;
}
I/O作业1
于 2024-03-28 20:50:31 首次发布