#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data_base{
char *name;
int age;
};
#define NAME_TAG "Name "
#define AGE_TAG "Age "
char* getName(char **p){
int tag_size = strlen(NAME_TAG);
if(strncmp(*p, NAME_TAG, tag_size)==0){
char *agep = strstr(*p += tag_size, AGE_TAG);
int len = agep - *p -1;//-1: for space before "Age"
char *name = calloc(len + 1, sizeof(char));
strncpy(name, *p, len);
*p = agep;
return name;
}
return NULL;
}
int getAge(char **p){
int tag_size = strlen(AGE_TAG);
if(strncmp(*p, AGE_TAG, tag_size)==0){
int age = (int)strtol(*p += tag_size, p, 10);
if(**p == ' ')
*p += 1;
return age;
}
return -1;
}
struct data_base *parse(char *data, size_t *size){
char *p = data;
struct data_base *dbp=NULL;
*size = 0;
while(*p){
*size += 1;
dbp = realloc(dbp, sizeof(struct data_base)*(*size));
dbp[*size -1].name = getName(&p);//this is treated as format is correct
dbp[*size -1].age = getAge(&p);
}
return dbp;//realloc(dbp, sizeof(struct data_base)*(*size));
}
int main(void){
char data[] = "Name Allan Age 35 Name John Age 50 Name Jim Age 20";
struct data_base *dbp;
size_t i, size;
dbp = parse(data, &size);
//check print
for(i = 0; i < size ;++i){
printf("Name: %s, Age: %d\n", dbp[i].name, dbp[i].age);
}
//deallocate
return 0;
}