#include <stdio.h> #include <stdlib.h>
struct ConfigInfo { char key[64]; char val[128]; };
int isvald(const char *buf) { if (buf[0] == '#' || buf[0] == '\n' || strchr(buf, ':') == NULL) return 0; return 1; }
int get_line(FILE *fp) { char buffer[1024] = { 0 }; int index = 0;
while (fgets(buffer, 1024, fp) != NULL) { if (!isvald(buffer)) continue; memset(buffer, 0, 1024); index++; } fseek(fp, 0, SEEK_SET); return index; }
void load(const char *path, char **data, int *len) { FILE *fp = fopen(path, "r");
int line = get_line(fp); char **tmp = malloc(sizeof(char *)* line);
char buf[1024] = { 0 }; int index = 0;
while (fgets(buf,1024,fp) != NULL) { if (!isvald(buf)) continue;
tmp[index] = malloc(strlen(buf) + 1); strcpy(tmp[index], buf); memset(buf, 0, 1024); ++index; }
*data = tmp; *len = line; fcloseall(); }
char * parser(char **data, int len, struct ConfigInfo **info,char *key) { struct ConfigInfo *my = malloc(sizeof(struct ConfigInfo) * len); memset(my, 0, sizeof(struct ConfigInfo) * len);
for (int x = 0; x < len; x++) { char *pos = strchr(data[x], ':');
strncpy(my[x].key, data[x], pos - data[x]); strncpy(my[x].val, pos+1 , strlen(pos+1) -1);
printf("key: %s --> val: %s \n", my[x].key,my[x].val);
if (strcmp(key, my[x].key) == 0) return my[x].val; }
for (int y = 0; y < len; ++y) { if (data[y] != NULL) free(data[y]); } }
int main(int argc, char * argv[]) { char *filedata = NULL; struct ConfigInfo *info = NULL; int lines = 0;
load("c:/conf.ini", &filedata, &lines);
char * user = parser(filedata, lines, &info,"username");
printf("username = %s", user);
system("pause"); return 0; }
|