Я пытаюсь написать анализатор INI в C. Я уже написал функцию, которая читает файл с произвольным количеством строк и символов в строках (функция с именем getLineOfAnySize здесь не показана). Теперь мне нужно хранить строки в структурах. Я думал о создании структуры с массивом структур, в которых есть структуры с ключами и значениями. (По крайней мере, я так думаю). Вопрос в том, можно ли сделать это как-нибудь проще? Если нет, может ли кто-нибудь помочь с передачей имен разделов, ключей и значений в четко определенные структуры?
Вот моя структура
struct Section {
char *name;
char **keys;
char **values;
};
Вот фрагмент кода для чтения файла .
int main(void)
{
FILE *fp = NULL; // file handle
char *line; //
int endOfLineDetected = 0;
size_t nrOfCharRead = 0;
LIST *current, *head; // pointers to list elements
head = current = NULL; // init to NULL
fp = fopen("test.ini", "r"); // open file for reading
int nr = 0;
while( line = getLineOfAnySize(fp,128,&endOfLineDetected,&nrOfCharRead) ){ // read the file
if( (nrOfCharRead == 0) && endOfLineDetected) break;
// create new list element
LIST *node = malloc (sizeof(LIST));
nr = nr + 1;
node->linia = line; // initialize the linia (diffrent name for line)
node->numer = nr; // update the line number
node->next = NULL; // next element do not exist yet
if(head == NULL)
{
current = head = node;
} else
{
current = current->next = node;
}
if (endOfLineDetected) break;
}
if (fp) fclose(fp); // remember to close the file
А вот в тот момент, когда у меня возникла проблема, я пытаюсь передать разделы, ключи и значения в подходящее место в структурах, но возникает ошибка сегментации (сбрасывается ядро).
int n = 0; // I am breaking the line where '=' occurs and recognizing values and keys by the reminder
int nsec = 0; // number of sections
struct Section **content = malloc(sizeof (struct Section*));
for(current = head; current ; current=current->next){
if (current->linia[0] == '['){
printf("sections %s \n", current->linia );
//content = realloc(content,(nsec+2)*sizeof(struct Section*));
//content[nsec] = malloc(sizeof(struct Section));
//content[nsec]->keys = malloc(sizeof(char*)+1);
//content[nsec]->keys[0] = malloc(sizeof(char)+128);
n = 0;
nsec++;
}
if (current->linia[0] != '[' && n % 2 == 0 && current->linia[0] != ';' && current->linia[0] != ';' && current->linia[0] != '\0'){
if (CheckNames(current->linia) == 0){
printf("values %s \n", current->linia );
}
else return 1; // place to return error if indentifier is invalid
}
if (current->linia[0] != '[' && n % 2 == 1 && current->linia[0] != ';' && current->linia[0] != '\0'){
if (CheckNames(current->linia) == 0){
printf("keys %s ", current->linia );
content[nsec]->keys[n] = strdup(current->linia);
content[nsec]->keys = realloc(content[nsec]->keys,(n+2)*(sizeof(char*)+1));
content[nsec]->keys[n+1] = malloc(sizeof (char)+128);
}
else return 1; // place to return error if indentifier is invalid
}
n++;
}
return 0;
}