(Added high score code from Adam Czachorowski)
[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 "high_scores.h"
14
15 FILE * opendata(char * mode)
16 {
17   char * filename, * home;
18   FILE * fi;
19
20
21 #ifdef LINUX
22   /* Get home directory (from $HOME variable)... if we can't determine it,
23      use the current directory ("."): */
24
25   if (getenv("HOME") != NULL)
26     home = getenv("HOME");
27   else
28     home = ".";
29
30
31   /* Create the buffer for the filename: */
32
33   filename = (char *) malloc(sizeof(char) * (strlen(home) +
34                                              strlen("/.supertux") + 1));
35
36   strcpy(filename, home);
37   /* Open the high score file: */
38
39       strcat(filename, "/.supertux");
40 #else
41       filename = "supertux.dat";
42 #endif
43
44
45       /* Try opening the file: */
46
47       fi = fopen(filename, mode);
48
49       if (fi == NULL)
50        {
51          fprintf(stderr, "Warning: I could not open the high score file ");
52
53          if (strcmp(mode, "r") == 0)
54            fprintf(stderr, "for read!!!\n");
55          else if (strcmp(mode, "w") == 0)
56            fprintf(stderr, "for write!!!\n");
57
58        }
59
60       return(fi);
61     }
62
63 /* Load data from high score file: */
64
65 int load_hs(void)
66 {
67   FILE * fi;
68   char temp[128];
69   int score = 100;
70
71   /* Try to open file: */
72
73   fi = opendata("r");
74   if (fi != NULL)
75     {
76       do
77         {
78           fgets(temp, sizeof(temp), fi);
79
80           if (!feof(fi))
81             {
82               temp[strlen(temp) - 1] = '\0';
83
84
85               /* Parse each line: */
86
87               if (strstr(temp, "highscore=") == temp)
88                 {
89                   score = atoi(temp + 10);
90
91                   if (score == 0)
92                     score = 100;
93                }
94             }
95         }
96       while (!feof(fi));
97
98       fclose(fi);
99     }
100   return score;
101 }
102
103 void save_hs(int score)
104 {
105   FILE * fi;
106
107
108   /* Try to open file: */
109
110   fi = opendata("w");
111   if (fi != NULL)
112     {
113       fprintf(fi, "# Supertux data file\n\n");
114
115       fprintf(fi, "highscore=%d\n", score);
116
117       fprintf(fi, "# (File automatically created.)\n");
118
119       fclose(fi);
120     }
121 }