Hi,
Klar:
Du baust einen einfachen Automaten, der die einliest.Datei öffnen.
Detie (zeilenweise) einlesen
mit z.B. strtok() key von value trennen
in eine linked list o.ä. speichern
fertigmit sowas habe ich gerechnet ;-)
Deshalb ja auch meine Frage weiter unten, wie Du auf die Idee kamst, so eine Frage ausgerechnet hier zu stellen ;-)
Aber weil ich ja heute meinen gutmütigen habe, etwas bräsig vor dem Rechner sitze und rein gar keine Lust habe etwas für meinen Lebensunterhalt zu tun ... äh ... was wollt' ich jetzt sagen? - ach ja: hier ein kurzes Snippet:
Gegeben sei eine simplifizierte INI-Datei wie sie vor rund 30 Jahren mal erfunden wurde (Ja, auch das ist nicht auf dem Mist von MS gewachsen ;-)
---config.data---
key1=value1;
key2 = value2,value3;
key3= value4,value5;
key4=;
---snap---
---parse.c---
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
typedef struct _config_t{
char *key;
char *value;
struct _config_t *next;
} *config_t;
char *strtrim(char *s){
char *last;
if(s){
while(isspace(*s))
s++;
last = s+strlen(s);
while (last > s){
if(!isspace(*(last - 1)))
break;
last--;
}
*last = '\0';
}
return s;
}
extern char *strdup(const char *s);
int main(){
char buffer[BUFSIZ];
FILE *configp;
config_t conf, start_conf;
uint8_t i = 0;
char *tmpp;
configp = fopen("config.file","r");
if(!configp){
fprintf(stderr,"fopen() failed: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
conf = malloc(sizeof(struct _config_t));
if(!conf){
fprintf(stderr,"malloc(1) failed: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
start_conf = conf;
while(fgets(buffer,BUFSIZ,configp) != NULL){
if(conf->next == NULL){printf("222 i = %d\n",i);
conf->next = malloc(sizeof(struct _config_t));}
if(!conf){
fprintf(stderr,"malloc(2) failed: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
conf->key = strdup(strtok(buffer,"="));
conf->value = strdup(strtok(NULL,"=;"));
conf = conf->next;
printf("i = %d\n",i++);
}
conf->next = NULL;
conf = start_conf;
/* TEST */
while(conf->next != NULL){
printf("KEY = %s ",strtrim(conf->key));
free(conf->key);
tmpp = strtok(conf->value,",");
i=1;
do{
printf("Value[%d] = %s, ",i++,strtrim(tmpp));
tmpp = strtok(NULL,",");
}while(tmpp != NULL);
putc('\n',stdout);
free(conf->value);
start_conf = conf->next;
free(conf);
conf = start_conf;
}
putc('\n',stdout);
exit(EXIT_SUCCESS);
}
---snap---
strdup() ist nicht in C99, aber schnell selber gebaut.
so short
Christoph Zurnieden