#include
#include
typedef struct person
{
char* last;
char* first;
char* year;
}person_t;
int main()
{
int i;
FILE *fp1,*fp2;
person_t *list =(person_t*)malloc(100*sizeof(person_t));
fp1=fopen("d.txt","r");
fp2=fopen("detail.txt","w");
if ((fp1 = fopen("d.txt", "r")) == NULL)
{
printf("Cannot open d.txt!\n");
exit(0);
}
for(i=0;i<5;i++)
{
(list+i)->first=(char*)malloc(sizeof(char)*20);//为你的指针分配空间
(list+i)->last=(char*)malloc(sizeof(char)*20);
(list+i)->year=(char*)malloc(sizeof(char)*20);
fscanf(fp1,"%s %s %s\n",(list+i)->first,(list+i)->last,(list+i)->year);
}
for(i=0;i<5;i++)
{
fprintf(fp2,"%s %s %s\n",(list+i)->first,(list+i)->last,(list+i)->year);
}
for(i=0;i<5;i++)
{
free((list+i)->first);//释放空间
free((list+i)->last);
free((list+i)->year);
}
fclose(fp1);
fclose(fp2);
return 0;
}
如果你不想指定分配的内存长度,你可以按照下面的方法:
#include
#include
#include
typedef struct person
{
char* last;
char* first;
char* year;
}person_t;
int main()
{
int i;
FILE *fp1,*fp2;
char str[20];
person_t *list =(person_t*)malloc(100*sizeof(person_t));
fp1=fopen("d.txt","r");
fp2=fopen("detail.txt","w");
if ((fp1 = fopen("d.txt", "r")) == NULL)
{
printf("Cannot open d.txt!\n");
exit(0);
}
for(i=0;i<5;i++)
{
fscanf(fp1,"%s",str);
(list+i)->first=(char*)malloc(sizeof(char)*(strlen(str)+1));//每次让str存放读取的数据,然后根据str长度malloc内存长度
strcpy((list+i)->first,str);
fscanf(fp1,"%s",str);
(list+i)->last=(char*)malloc(sizeof(char)*(strlen(str)+1));
strcpy((list+i)->last,str);
fscanf(fp1,"%s",str);
(list+i)->year=(char*)malloc(sizeof(char)*(strlen(str)+1));
strcpy((list+i)->year,str);
}
for(i=0;i<5;i++)
{
fprintf(fp2,"%s %s %s\n",(list+i)->first,(list+i)->last,(list+i)->year);
}
for(i=0;i<5;i++)
{
free((list+i)->first);//释放空间
free((list+i)->last);
free((list+i)->year);
(list+i)->first=NULL;//防止野指针出现
(list+i)->last=NULL;
(list+i)->year=NULL;
}
fclose(fp1);
fclose(fp2);
return 0;
}