将列表写入文件

时间:2015-01-27 09:56:32

标签: c struct

我将列表写入文件时遇到问题。请检查我的代码。

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

typedef struct record
{
   char name[30];
   int score;
} record;

int score = 23;
char winner[30] = "gracz";

typedef struct el_list
{
   record record;
   struct el_list* next;
} el_list;

el_list *first = NULL;

int addrecord()
{
   el_list *record;
   record = (el_list*) malloc (sizeof(el_list));
   record->next = NULL;
   record->record.score = score;
   strcpy(record->record.name, winner);
   return record;
}

void addtolist(el_list** first)
{
   el_list *pom, *tmp = addrecord();

   if (*first == NULL)
      *first = tmp;
   else if ((*first)->record.score > tmp->record.score)
   {
      tmp->next = *first;
      *first = tmp;
   }
   else
   {
      pom = (*first);
      while((pom->next != NULL) && (pom->record.score < tmp->record.score))
         pom = pom->next;
      tmp->next = pom->next;
      pom->next = tmp;
   }
}

void save2file(el_list* first)
{
   el_list *tmp;
   FILE *hs = fopen("highscores.txt", "w");
   if( hs == NULL)
      perror("Blad z plikiem.");
   else
   {
      tmp = first;
      while(tmp != NULL)
      {
         fprintf( hs, "%d %s\n", score, winner);
         tmp = tmp->next;
      }
   }
   fclose(hs);
}

int main()
{
   addtolist(&first);
   save2file(&first);
   return 0;
}

在save2file中可能有问题。

抱歉我的英文。 ;)

1 个答案:

答案 0 :(得分:2)

您正在保存scorewinner,这些是与tmp中当前列表项无关的全局变量。

另外,为了清楚起见,您应该以文本模式打开输出文件,即使用fopen("highscores.txt", "wt")