70,037
社区成员
发帖
与我相关
我的任务
分享#include <string.h>
#include <stdio.h>
#define L sizeof(struct yuan)
struct yuan //将文件读出后存放的结构体
{
// char *string;
int age;
int pay;
struct yuan *next;
};
int n;
struct str //用于临时存放读取文件的字符串
{
char _str[25];
}X[5];
analysis_creat() //解析文件,创建链表
{
int i,j,a[5],b[5];
char *p=NULL,*buffer=NULL,*delims={","};
struct yuan *head,*p1,*p2;
head=NULL;
p1=p2=NULL;
n=0;
p1=p2=(struct yuan *)malloc(L);
for(i=0;i<5;i++)
{
n=n+1;
if(n=1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct yuan *)malloc(L);
buffer=strdup(X[i]._str);
p=strtok(buffer,delims); //name子串
p=NULL;
p=strtok(NULL,delims); //age字串
p1->age=atoi(p);
printf("%d ",p1->age);
p=NULL;
p=strtok(NULL,delims); //pay字串
p1->pay=atoi(p);
printf("%d ",p1->pay);
printf("\n");
}
p2->next=NULL;
return(head);
}
void show(struct yuan *head) //链表遍历输出函数
{
struct yuan *p;
if(head==NULL) printf("链表为空,没有数据\n");
else printf("\n链表的数据元素为:\n");
for(p=head;p!=NULL;p=p->next)
printf("%d %d",p->age,p->pay);
printf("\n");
}
int main(int argc,char **argn)
{
struct yuan *h1;
int i,*p,j;
FILE *fp;
h1=NULL;
fp=fopen("test.txt","r");
for(i=0;i<5&&!feof(fp);i++)
fscanf(fp,"%s ",X[i]._str);
printf("\n");
analysis_creat();
show(h1);
fclose(fp);
return 0;
}