把固定格式文件读入链表,把test.txt放在同一文件夹下
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node *create();
struct node
{
int
numberical;
long serialnumber;
char sort;
char date[10];
struct node *next;
};
struct node *create()
{
FILE *fp;
struct node *head, *tail, *p;
char bal[30];
int i,j=0,n=0;
int max=0;
head = tail =NULL;
if(!(fp = fopen("test.txt","r")))
{
printf("cannot open file,\n");
exit(1);
}
while(!feof(fp))
{
p = (struct node *)malloc(sizeof(struct node));
n=0;
j=0;
if(fgets(bal,19,fp))
{
for(i=0;i<(int)strlen(bal);i++)
{
if(i == 0)
p -> numberical = bal[i]-'0';
else if(i>1 && i<10)
{
n = n*10+bal[i]-'0';
p -> serialnumber = n;
}
else if(i>10 && i<12)
p -> sort = bal[i];
else if(i>12 && i<17)
{
p -> date[j] = bal[i];
j++;
}
}
p -> date[4]='\0';
p -> next = NULL;
if(head == NULL)
head = tail = p;
else
{
tail -> next = p;
tail = p;
}
}
}
fclose(fp);
return(head);
}
int main(void)
{
struct node *q;
q=create();
while(q != NULL)
{
printf("%d ",q -> numberical);
printf("%ld ",q -> serialnumber);
printf("%c ",q -> sort);
printf("%s",q -> date);
q = q -> next;
printf("\n");
}
return 0;
}
/* 以下是test.txt文本文件保持原来格式*/
1 20080909 R 88.7
2 30080909 f 89.8
3 40080909 e 89.9
4 50080909 g 90.9
5 60080909 h 100