#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
键值对文件的可移植的小模块
供以后备查