Читач конфігураційного файлу на C

[СЕРВЕР]
SERVERADDR = localhost
SERVER
PORT = 8080
SERVER_DOMAIN = domain.com

[СТОРІНКИ\page1]
PAGEURL = /home
PAGE
ID = 0

[СТОРІНКИ\page2]
PAGEURL = /about
PAGE
ID = 1
```

char* read(const char* filename) {  
 FILE* file = fopen(filename, "r");  
 if (file == NULL) {  
 return NULL;  
 }  

 fseek(file, 0, SEEK_END);  
 long fileSize = ftell(file);  
 if (fileSize < 0) {  
 fclose(file);  
 return NULL;  
 }  
 fseek(file, 0, SEEK_SET);  

 char* content = (char*)malloc(fileSize + 1);  
 if (content == NULL) {  
 fclose(file);  
 return NULL;  
 }  

 size_t bytesRead = fread(content, 1, fileSize, file);  
 content[bytesRead] = ‘\0';  

 fclose(file);  

 return content;  
}
char** tokenize(const char* content, int* count) {  
 const char* delimiters = " ";  
 const char* specialChars = "=;\"’";  
 char* token;  
 char* contentCopy = strdup(content);  
 char** tokenList = NULL;  
 *count = 0;  

 token = strtok(contentCopy, delimiters);  
 while (token) {  
 while (*token) {  
 if (strchr(specialChars, *token)) {  
 // Додати спеціальний символ як окремий токен  
 tokenList = (char**)realloc(tokenList, (*count + 1) * sizeof(char*));  
 tokenList[*count] = (char*)malloc(2);  
 tokenList[*count][0] = *token;  
 tokenList[*count][1] = ‘\0';  
 (*count)++;  
 token++;  
 } else {  
 // Додати неперервні не-спеціальні символи як токен  
 size_t len = 0;  
 while (token[len] && !strchr(specialChars, token[len])) {  
 len++;  
 }  
 tokenList = (char**)realloc(tokenList, (*count + 1) * sizeof(char*));  
 tokenList[*count] = strndup(token, len);  
 (*count)++;  
 token += len;  
 }  
 }  

 token = strtok(NULL, delimiters);  
 }  

 free(contentCopy);  
 return tokenList;  
}




Перекладено з: [Config File Reader in C](https://medium.com/@fgmfndych/how-i-made-a-tokenizer-parser-in-the-language-of-c-ccb36a1def5e)

Leave a Reply

Your email address will not be published. Required fields are marked *