求问?帮看下程序。为什么存入结构体至文件中其文件格式不是TXT而是“文件”格式?
#include<stdio.h>#include<stdlib.h>
#include<string.h>
struct node
{
char serial_num[20];
struct node *next;
};
int n1=0,n2=0;
void SaveList(struct node * head)
{
printf("input the file name:\n");
char name[20]={0};
FILE * fp;
scanf("%s",name);
if((fp=fopen(name,"w"))==NULL)
{printf("NO\n");exit(0);}
struct node * p1,* p2;
p2=head;
p1=head->next;
for(;(p1!=NULL)&&(p1!=head);)
{
if(fwrite(p2,sizeof(struct node),1,fp)!=1)
{printf("Wrong\n");fclose(fp);}
p2=p1;
p1=p1->next;
}
fclose(fp);
}
struct node * LoadList(int n)
{
FILE * fp;
char name[20];
printf("please input the file to open:\n");
scanf("%s",name);
if((fp=fopen(name,"r"))==NULL)
{printf("NO\n");exit(0);}
struct node * p1,* p2,* head;
p1=p2=(struct node *)malloc(sizeof(struct node));
head=p1;
for(;;)
{
fread(p1,sizeof(struct node),1,fp);
if(p1->next==NULL||p1->next==head){p1->next=NULL;break;}
n++;
p1=(struct node *)malloc(sizeof(struct node));
p2->next=p1;
p2=p1;
}
fclose(fp);
return(head);
}
void PrintList(struct node * head,int n)
{
struct node * p=head;
int i;
for(i=0;i<n;i++,p=p->next)
printf("%s ",p->serial_num);
printf("\n");
}
void ChangeList(struct node * head,int n)
{
struct node * p1,* p2;
int i,j;
char t[20]={0};
for(i=0;i<n-1;i++)
{
p2=head;
p1=head->next;
for(j=0;j<n-1-i;j++)
{
if(strcmp(p1->serial_num,p2->serial_num)<0)
{strcpy(t,p1->serial_num);strcpy(p1->serial_num,p2->serial_num);strcpy(p2->serial_num,t);}
p2=p1;p1=p1->next;
}
}
}
void main()
{
struct node * p1,* p2,* h1,* head,* rear;
printf("please input the list1:\n");
p1=(struct node *)malloc(sizeof(struct node));
h1=p1;
for(;;)
{
scanf("%s",&p1->serial_num);
if(strcmp(p1->serial_num,"0")==0)
{
p2->next=h1;
rear=p2;
break;
}
n1++;
ChangeList(h1,n1);
PrintList(h1,n1);
p2=p1;
p1=(struct node *)malloc(sizeof(struct node));
p2->next=p1;
}
printf("please input the list2:\n");
p1=(struct node *)malloc(sizeof(struct node));
head=p1;
for(;;)
{
scanf("%s",&p1->serial_num);
if(strcmp(p1->serial_num,"0")==0)
{
p2->next=NULL;
break;
}
n2++;
ChangeList(head,n2);
PrintList(head,n2);
p2=p1;
p1=(struct node *)malloc(sizeof(struct node));
p2->next=p1;
}
SaveList(h1);
SaveList(head);
n1=0;n2=0;
h1=LoadList(n1);
PrintList(h1,n1);
head=LoadList(n2);
PrintList(head,n2);
for(p1=h1;p1->next!=NULL;p1=p1->next);
p1->next=head;
PrintList(h1,n1+n2);
SaveList(h1);
}
[ 本帖最后由 世界你好 于 2014-1-2 10:57 编辑 ]