source: Daodan/src/Inifile_Reader.c@ 1009

Last change on this file since 1009 was 993, checked in by alloc, 11 years ago

Daodan:

File size: 1.4 KB
RevLine 
[346]1#include <stdio.h>
2#include <stdlib.h>
[692]3#include "stdint.h"
[346]4#include <string.h>
5#include <ctype.h>
6
[692]7#include "Inifile_Reader.h"
[451]8
[993]9static char* strtrim(char* string)
[349]10{
[993]11 while (isspace(*string))
12 string++;
13 for (int i = strlen(string) - 1; i >= 0; i--)
14 {
15 if (isspace(string[i]))
16 {
17 string[i] = 0;
18 }
[466]19 else
[993]20 {
[451]21 break;
[993]22 }
23 }
24 return string;
[451]25}
26
[993]27static char* newlines(char* string)
[451]28{
[993]29 for (char* i = string + strlen(string) - 1; i >= string; i--)
[349]30 {
[993]31 if ((*i == '\\') && (*(i+1) == 'n'))
[451]32 {
[993]33 *i = '\n';
34 memmove(i+1, i+2, strlen(i+1));
[451]35 }
[349]36 }
[993]37 return string;
[349]38}
[451]39
[993]40bool Inifile_Read(const char* filename, inifile_callback callback)
[346]41{
42 FILE* fp = fopen(filename, "r");
[993]43
44 char inisection[30] = "";
45 char option[30] = "";
46 char value[200] = "";
47
[346]48 char readbuf[4096] = "";
49 char* readptr;
[993]50
[346]51 bool success = true;
52
53 if (!fp)
[993]54 return false;
[346]55
56 while ((readptr = fgets(readbuf, sizeof(readbuf), fp))) // Loop through each line.
57 {
58 while (isspace(readptr[0])) // Skip whitespace.
59 readptr++;
[993]60
[346]61 if (readptr[0] == '\0' || readptr[0] == '#' || readptr[0] == '!') // Skip empty lines and comments.
62 continue;
[993]63
64 if (sscanf(readptr, "[%[^]]]", inisection) == 1)
[346]65 {
66 }
[993]67 else if (sscanf(readptr, "%[^=]=%[^\n]", option, value) == 2)
[346]68 {
[993]69 callback(inisection, strtrim(option), newlines(strtrim(value)));
[346]70 }
[993]71 else
72 {
73 success = false;
74 }
[346]75 }
76
77 fclose(fp);
78 return success;
79}
[993]80
Note: See TracBrowser for help on using the repository browser.