私はあなたの所有ペットの数を最初に尋ね、次に各ペットの名前と年齢を構造体(すべてリンクリストを使用)に保存するこのプログラムを作成しました。リンクリストのデータをC言語のtxtファイルに書き込む
私の質問は:手順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:グローバル変数 – developer