用fscanf和fprintf,如果是C++的话用fstream更加方便。
例拍者悔如写袭正文件,如果你想每一行放一个链表,可以这么写
FILE *f=fopen("嫌茄abc.txt");
//然后对链表每一个元素
fprintf(f,"%s %d %f %f\n",name,&no,&workday,&workyear);
fclose(f);
然后你打开abc.txt,看看它是怎么存的。
读文件刚好相反,用scanf:
FILE *f=fopen("abc.txt");
//然后对文件的每一行,读到变量里
while(fscanf(f,"%s %d %f %f\n",name,&no,&workday,&workyear)!=EOF)
{
吧name,no,...赋值到链表里面
}
fclose(f);
#include
#include
struct date
{
char str[3];
struct date *next;
};
//链表长度为len
struct 喊首date *create_link(int len)
{
struct date *head;
struct date *tmp;
int i;
head = malloc(sizeof(struct date));
tmp = head;
for(i = 1; i < len; ++i)
{
郑稿数 head ->next = malloc(sizeof(struct date));
head = head ->next;
}
head ->next = NULL;
return tmp;
}
//读文件到链表
void read_file_to_link(struct date *head,FILE *fp)
{
if(head == NULL || fp == NULL)
{
fprintf(stderr,"null pointer");
exit(EXIT_FAILURE);
}
do
{
fscanf(fp,"%3s",head ->str);
head = head ->next;
}while(head != NULL);
}
//显示链表中的内容
void print_link(struct date *head)
{
if(head == NULL)
{
fprintf(stderr,"null pointer");
exit(EXIT_FAILURE);
}
do
{
printf("%s",head ->str);
head = head ->next;
}while(head != NULL);
}
int main()
{
FILE *fp;
int len; //链表长度
敬冲 scanf("%d",&len);
fp = fopen("a.txt","r");
struct date *head;
head = create_link(len);
read_file_to_link(head,fp);
print_link(head);
exit(EXIT_SUCCESS);
}
这么难,高手!^-^