【发布时间】:2016-11-14 15:57:21
【问题描述】:
我创建了这个程序,它首先询问您拥有多少只宠物,然后将每只宠物的姓名和年龄存储在一个结构中(全部使用链表)。
我的问题是:我正在尝试使用过程writeToFile() 将数据写入 .txt 文件,但在执行时,.txt 文件不包含任何数据。我不明白为什么?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct Node {
char *name;
int age;
struct Node *next;
};
struct Node * petRecord;
struct Node * newRecord;
void printPetRecord()
{
while(petRecord != NULL)
{
printf("Name of Pet: %s\n", petRecord->name);
printf("Age of Pet: %d\n", petRecord->age);
petRecord = petRecord->next;
}
}
void writeToFile()
{
FILE * fptr;
fptr = fopen("petnames.txt", "w");
if(fptr==NULL)
{
printf("Error\n");
}
else
{
while(petRecord != NULL)
{
fprintf(fptr, "\nPet Name: %s\nAge: %d\n", petRecord->name, petRecord->age);
petRecord = petRecord->next;
}
}
fclose(fptr);
}
int main()
{
int count, i;
printf("How many pets do you have? ");
scanf("%d", &count);
for(i=0; i<count; i++)
{
if(i==0)
{
petRecord = malloc(sizeof(struct Node));
newRecord = petRecord;
}
else
{
newRecord->next = malloc(sizeof(struct Node));
newRecord = newRecord->next;
}
newRecord->name = malloc(50*sizeof(char));
printf("Name of Pet: ");
scanf("%s", newRecord->name);
printf("Age of Pet: ");
scanf("%d", &newRecord->age);
}
newRecord->next = NULL;
printf("\n\n");
printPetRecord();
writeToFile();
}
【问题讨论】:
-
您是否尝试将其打印在标准输出上?
-
不要使用全局变量。
-
@Katrina:当您直接使用全局变量进行迭代时,您丢失了列表头
标签: c linked-list