summaryrefslogtreecommitdiff
path: root/ini.c
blob: 90f6a562642a1726b5433967ea258d47209ead21 (plain)
    1 //  Cini is a command line tool to parse ini files
    2 //  Copyright (C) 2018  Aaron Ball <nullspoon@oper.io>
    3 // 
    4 //  This program is free software: you can redistribute it and/or modify
    5 //  it under the terms of the GNU General Public License as published by
    6 //  the Free Software Foundation, either version 3 of the License, or
    7 //  (at your option) any later version.
    8 // 
    9 //  This program is distributed in the hope that it will be useful,
   10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
   11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   12 //  GNU General Public License for more details.
   13 // 
   14 //  You should have received a copy of the GNU General Public License
   15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
   16 
   17 #include "ini.h"
   18 
   19 int ini_getbykey(char* path, char* reqkey) {
   20   FILE* fd; // File descriptor for ini file
   21   char buf[1024];
   22   char key[512];
   23 
   24   fd = fopen(path, "r");
   25 
   26   while(fgets(buf, 1024, fd) != NULL) {
   27     trim(buf, buf);
   28     // Don't care about empty lines or section headers
   29     if(strcmp(buf, "") == 0 || buf[0] == '[')
   30       continue;
   31 
   32     split(buf, ' ', 0, key);
   33     if(strcmp(key, reqkey) == 0) {
   34       printf("key: %s\n", key);
   35     }
   36   }
   37 
   38   fclose(fd);
   39   return 0;
   40 }
   41 
   42 int ini_getsection(char* path, char* reqsection, int hidekeys) {
   43   FILE* fd; // File descriptor for ini file
   44   char buf[512];
   45   char section[512] = "";
   46   int  linelen = 0;
   47   char print[512];
   48 
   49   fd = fopen(path, "r");
   50   if(!fd) { 
   51     fprintf(stderr, "Could not open file %s\n", path);
   52     return 1;
   53   }
   54 
   55   while(fgets(buf, 512, fd) != NULL) {
   56     trim(buf, buf);
   57     if(strcmp(buf, "") == 0)
   58       continue;
   59 
   60     linelen = strlen(buf);
   61 
   62     if(buf[0] == '[') {
   63       strncpy(section, &buf[1], linelen - 2);
   64       section[linelen - 2] = '\0';
   65       continue;
   66     }
   67 
   68     if(strcmp(reqsection, section) == 0) {
   69       if(hidekeys == 1) {
   70         // Split by =, grab col 1 (not 0)
   71         split(buf, '=', 1, print);
   72         // Trim leading and trailing whitespace
   73         trim(print, print);
   74         printf("%s\n", print);
   75       } else {
   76         printf("%s\n", buf);
   77       }
   78     }
   79   }
   80 
   81   fclose(fd);
   82   return 0;
   83 }

Generated by cgit