Huge code merge. This reflects the current status of my rewrite/restructuring. A...
[supertux.git] / src / high_scores.c
1 /*
2  
3   by Adam Czachorowski
4   gislan@o2.pl
5  
6 */
7
8 /* Open the highscore file: */
9
10 #include <string.h>
11 #include <stdlib.h>
12
13 #include "globals.h"
14 #include "high_scores.h"
15
16 FILE * opendata(char * mode)
17 {
18   char * filename;
19   FILE * fi;
20
21
22   filename = (char *) malloc(sizeof(char) * (strlen(st_dir) +
23                              strlen("/st_highscore.dat") + 1));
24
25   strcpy(filename, st_dir);
26   /* Open the high score file: */
27   
28 #ifdef LINUX
29   strcat(filename, "/highscore");
30 #else
31 #ifdef WIN32
32  strcat(filename, "/st_highscore.dat");
33  #endif
34 #endif
35
36
37   /* Try opening the file: */
38
39   fi = fopen(filename, mode);
40   free( filename );
41   
42   if (fi == NULL)
43     {
44       fprintf(stderr, "Warning: I could not open the high score file ");
45
46       if (strcmp(mode, "r") == 0)
47         fprintf(stderr, "for read!!!\n");
48       else if (strcmp(mode, "w") == 0)
49         fprintf(stderr, "for write!!!\n");
50
51     }
52
53   return(fi);
54 }
55
56 /* Load data from high score file: */
57
58 int load_hs(void)
59 {
60   FILE * fi;
61   char temp[128];
62   int score = 100;
63
64   /* Try to open file: */
65
66   fi = opendata("r");
67   if (fi != NULL)
68     {
69       do
70         {
71           fgets(temp, sizeof(temp), fi);
72
73           if (!feof(fi))
74             {
75               temp[strlen(temp) - 1] = '\0';
76
77
78               /* Parse each line: */
79
80               if (strstr(temp, "highscore=") == temp)
81                 {
82                   score = atoi(temp + 10);
83
84                   if (score == 0)
85                     score = 100;
86                 }
87             }
88         }
89       while (!feof(fi));
90
91       fclose(fi);
92     }
93   return score;
94 }
95
96 void save_hs(int score)
97 {
98   FILE * fi;
99
100
101   /* Try to open file: */
102
103   fi = opendata("w");
104   if (fi != NULL)
105     {
106       fprintf(fi, "# Supertux highscore file\n\n");
107
108       fprintf(fi, "highscore=%d\n", score);
109
110       fprintf(fi, "# (File automatically created.)\n");
111
112       fclose(fi);
113     }
114 }