Advertisement
cd62131

(set|get)_level

Jul 20th, 2017
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. static bool invalid_level(int);
  6. static int get_level(const char *);
  7. static void set_level(const char *, int);
  8.  
  9. static const char *level_file = "typing.ini";
  10.  
  11. int main(void) {
  12.   puts("set 1"); set_level(level_file, 1);
  13.   printf("level: %d\n", get_level(level_file));
  14.   puts("set 10"); set_level(level_file, 10);
  15.   printf("level: %d\n", get_level(level_file));
  16.   puts("set 5"); set_level(level_file, 5);
  17.   printf("level: %d\n", get_level(level_file));
  18. }
  19.  
  20. static bool invalid_level(int level) {
  21.   return level < 1 || 8 < level;
  22. }
  23.  
  24. static int get_level(const char *fname) {
  25.   FILE *in = fopen(fname, "r");
  26.   int level;
  27.   fscanf(in, "%d", &level);
  28.   fclose(in);
  29.   if (invalid_level(level)) {
  30.     return 1;
  31.   }
  32.   return level;
  33. }
  34.  
  35. static void set_level(const char *fname, int level) {
  36.   if (invalid_level(level)) {
  37.     return;
  38.   }
  39.   FILE *out = fopen(fname, "w");
  40.   fprintf(out, "%d\n", level);
  41.   fclose(out);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement