#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct
{
char name[20];
int age;
int gender;
} student;
typedef struct LNode
{
student stuInfo;
struct LNode *next;
} LNode, *LinkList;
bool initList(LinkList &L)
{
L = (LNode *)malloc(sizeof(LNode));
L->next = NULL;
return true;
}
bool ListInsert(LinkList &L, student std)
{
LNode *P = L; // 用指针p指向当前扫描到的结点
while (P->next != NULL)
{
P = P->next;
} // 使用P指针向后遍历一直遍历到最后一个结点
LNode *S = (LNode *)malloc(sizeof(LNode)); // 创建新结点
S->next = NULL; // 让S作为新的尾结点
S->stuInfo = std; // 保存数据
P->next = S; // 将尾结点的指针指向新结点
return true;
}
bool outputFile(LinkList L)
{
FILE *ofp = NULL;
ofp = fopen("studentInfo.txt", "w");
if (ofp == NULL)
{
printf("文件创建失败");
return false;
}
LNode *P = L;
while (P->next != NULL)
{
P = P->next;
fprintf(ofp, "%s %d %d ", P->stuInfo.name, P->stuInfo.age, P->stuInfo.gender);
}
fclose(ofp);
return true;
}
int main()
{
student std;
LinkList L;
initList(L);
do
{
scanf("%s %d %d", &std.name, &std.age, &std.gender);
ListInsert(L, std);
} while (getchar() != '#');
outputFile(L);
return 0;
}
运行结果如下: