将列表写入文件

Writing list to file

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

#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 中遇到了问题。

对不起我的英语。 ;)

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

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