读文件KEY VALUE对的小模块

22 篇文章 0 订阅
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

#define CHAR_IS_IN_STR(c, s)  (NULL != strchr((s), (c)))
#define CHAR_ISNOT_IN_STR(c, s)  (NULL == strchr((s), (c)))
#define ARRAY_SIZE(A) (sizeof (p) / sizeof (*p))
#define SKIP_WHITESPACE(s) \
    do {\
        while (*s == ' ' \
                || *s == '\t') \
            ++s;\
    } while (0)

static bool find_token(char const **p, const char *strTok)
{
    const char *s1 =*p, *s2;
    
    SKIP_WHITESPACE(s1);
    
    for (s2 = strTok; ;s1++, s2++)
    {
        if (*s2 == '\0')
            break;
        
        if (*s1 != *s2)
            return false;
    }

    SKIP_WHITESPACE(s1);
    
    *p = s1;
    return true;
}

static bool do_parse(char *strValue, char *strBuf, const char *strKey, int nLen)
{
    int n1 = 0, n2 = 0, i;
    const char *p = strBuf;
    const char *pp[] = {"[", strKey, "]", "="};

    for (i = 0; i < ARRAY_SIZE(pp); i++)
        if (find_token(&p, pp[i]) == false)
            return false;

    for (i = 0; 
            i < nLen && 
            CHAR_ISNOT_IN_STR(*p, " \t\r\n") && 
            ('\0' != *p); 
            i++)
        *strValue++ = *p++;

    return true;
}

static bool read_value(const char *fname, const char *strKey, char *strValue, int nLen)
{
    static char buf[1024];
    FILE *fp = fopen(fname, "r");
    bool ret = false;
    
    while (fgets(buf, 1024, fp))
    {
        if (buf[0] == '\0')
            continue;
        
        ret = do_parse(strValue, buf, strKey, nLen);
        buf[0] = '\0';
        if (ret == true)
            break;
    }

    fclose(fp);
    return ret;
}

int main(int argc, char **argv)
{
    char s[100] = "";
    
    if (read_value(argv[1], argv[2], s, 100))
        printf("%s\n", s);

    return 0;
}

读类似

[keyname1] = value1 

    [   keyname2    ]     =               value2 

[keyname3   ] =          value3             


键值对文件的可移植的小模块
供以后备查

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值