C language read configuration file

(1) Prepare the configuration file, which is called config.ini under the source code path, and the content inside is

[IPSite]
socketOneIp=127.0.0.1
socketOnePort=6001
socketTwoIp=127.0.0.1
socketTwoPort=6002

[Timer] #Unit
milliseconds
timeCommand=5000
timePara=4000

(2) Define the function

const int MAX_KEY_NUM = 128;
const int MAX_KEY_LENGTH = 1024;

char gKeys[MAX_KEY_NUM][MAX_KEY_LENGTH];

char *GetIniKeyString(char *title, char *key, char *filename)
{
    FILE *fp;
    int  flag = 0;
    char sTitle[32], *wTmp;
    char sLine[MAX_KEY_LENGTH];

    sprintf(sTitle, "[%s]", title);
    if (NULL == (fp = fopen(filename, "r")))
    {
        perror("fopen");
        return NULL;
    }

    while (NULL != fgets(sLine, MAX_KEY_LENGTH, fp))
    {
        /// 这是注释行  ///
        if (0 == strncmp("//", sLine, 2)) continue;
        if ('#' == sLine[0])              continue;

        wTmp = strchr(sLine,'=');
        if ((NULL != wTmp) && (1 == flag))
        {             if (0 == strncmp(key, sLine, wTmp-sLine)) /// length depends on file Reading prevail ///             {                 sLine[strlen(sLine)-1] ='\0';                 fclose(fp);                 return wTmp + 1;             }         }         else         {             if (0 == strncmp(sTitle, sLine, strlen (sLine)-1)) /// The length depends on the file read ///             {                 flag = 1; /// Find the title position ///             }         }     }     fclose(fp);     return NULL; }

















(3) Calling process

char * ipOne =  (char*)malloc(100 * sizeof(char));
    strcpy(ipOne,GetIniKeyString("IPSite", "socketOneIp", "config.ini"));    
    printf("ipOne is %s\n", ipOne);

    char * portOne  =  (char*)malloc(100 * sizeof(char));
    strcpy(portOne,GetIniKeyString("IPSite", "socketOnePort", "config.ini"));
    printf("portOne is %s\n", portOne);

    char * ipTwo  =  (char*)malloc(100 * sizeof(char));
    strcpy(ipTwo,GetIniKeyString("IPSite", "socketTwoIp", "config.ini"));
    printf("ipTwo is %s\n", ipTwo);

    char * portTwo  =  (char*)malloc(100 * sizeof(char));
    strcpy(portTwo,GetIniKeyString("IPSite", "socketTwoPort", "config.ini"));
    printf("portTwo is %s\n", portTwo);

(4) Perfect function.

 

Guess you like

Origin blog.csdn.net/qq_14874791/article/details/108823552