2016-11-14 2 views
2

Я создал эту программу, которая сначала спросит, сколько у вас домашних животных, а затем сохраняет имя и возраст каждого питомца в структуре (все с помощью связанных списков).Запись данных из связанного списка в txt-файл в C

Мой вопрос: Я пытаюсь записать данные в .txt-файл, используя процедуру writeToFile(), но после выполнения. 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(); 
} 
+1

Вы пытались распечатать его на стандартный вывод, а? –

+0

Не используйте глобальные переменные. –

+0

@ Katrina: вы потеряли головку своего списка, когда вы перебираете напрямую глобальную переменную – developer

ответ

3

Ваша функция printPetRecord() оставляет указатель установлен на нуль.

Внутри printPetRecord() сделать что-то вроде этого:

struct Node * iterator = petRecord; 

, а затем itertae с помощью итератора.

#include <stdio.h> 
#include <stdlib.h> 

struct Node { 
    char *name; 
    int age; 
    struct Node *next; 
}; 

struct Node * petRecord; 
struct Node * newRecord; 

void printPetRecord() 
{ 
    struct Node * iterator = petRecord; 
    while(iterator != NULL) 
    { 
     printf("Name of Pet: %s\n", iterator->name); 
     printf("Age of Pet: %d\n", iterator->age); 
     iterator=iterator->next; 
    } 
} 

void writeToFile() 
{ 
    FILE * fptr; 
    fptr = fopen("petnames.txt", "w"); 
    struct Node * iterator = petRecord; 

    if(fptr==NULL) 
    { 
     printf("Error\n"); 
    } 

    else 
    { 
     while(iterator!= NULL) 
     { 
      fprintf(fptr, "\nPet Name: %s\nAge: %d\n", iterator->name, iterator->age); 
      iterator= iterator->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(); 
} 

Исполнение:

> gcc -o main main.c 
> ./main 
How many pets do you have? 2 
Name of Pet: a 
Age of Pet: 2 
Name of Pet: b 
Age of Pet: 3 


Name of Pet: a 
Age of Pet: 2 
Name of Pet: b 
Age of Pet: 3 
> cat petnames.txt 

Pet Name: a 
Age: 2 

Pet Name: b 
Age: 3 
+3

Это еще раз показывает, что глобальные переменные являются злыми. –

+0

Сделав это [struct Node * iterator = petRecord], я создаю новый узел, который указывает на адрес первого значения моего связанного списка. Итак, чтобы записать данные в txt-файл, я бы это сделал: while (iterator! = NULL) { \t fprintf (fptr, "\ nПоказать имя:% s \ nAge:% d \ n", iterator-> name, iterator-> возраст); \t iterator = iterator-> next; } У меня все еще нет данных в моем файле:/ – Katrina

+0

Работает для меня :) – mko

Смежные вопросы