2010-11-20 209 views
0

gcc 4.5.1 c89从文件中读取文本行

我正在使用以下代码从配置文件中读取一行文本。目前配置文件很小,会随着新的字段的增加而增长。而且我几乎可以设计出配置文件看起来像我自己。所以,我在下面的方式来完成它:

的config.cfg

# Configuration file to be loaded 

# protocol to use either ISDN, SIP, 
protocol: ISDN 

# run application in the following mode, makecall or waitcall 
mode: makecall 

我已经使用冒号的方式来搜索,将需要配置的类型。我只是想知道是否有更好的方法来做到这一点?

我的代码我用的是如下:

static int load_config(FILE *fp) 
{ 
    char line_read[LINE_SIZE] = {0}; 
    char *type = NULL; 
    char field[LINE_SIZE] = {0}; 
    char *carriage_return = NULL; 

    /* Read each line */ 
    while(fgets(line_read, LINE_SIZE, fp) != NULL) { 
     if(line_read != NULL) { 
      /* Ignore any hashs and blank lines */ 
      if((line_read[0] != '#') && (strlen(line_read) > 1)) { 
       /* I don't like the carriage return, so remove it. */ 
       carriage_return = strrchr(line_read, '\n'); 
       if(carriage_return != NULL) { 
        /* carriage return found so relace with a null */ 
        *carriage_return = '\0'; 
       } 

       /* Parse line_read to extract the field name i.e. protocol, mode, etc */ 
       parse_string(field, line_read); 
       if(field != NULL) { 
        type = strchr(line_read, ':'); 
        type+=2; /* Point to the first character after the space */ 

        if(strcmp("protocol", field) == 0) { 
         /* Check the protocol type */ 
         printf("protocol [ %s ]\n", type); 
        } 
        else if (strcmp("mode", field) == 0) { 
         /* Check the mode type */ 
         printf("mode [ %s ]\n", type); 
        } 
       } 
      } 
     } 
    } 

    return TRUE; 
} 

/* Extract the field name for the read in line from the configuration file. */ 
static void parse_string(char *dest, const char *string) 
{ 
    /* Copy string up to the colon to determine configuration type */ 
    while(*string != ':') { 
     *dest++ = *string++; 
    } 
    /* Insert nul terminator */ 
    *dest = '\0'; 
} 

回答

1

容易应该是:

static int load_config(FILE *fp) 
{ 
    int r=0; 
    char line[LINE_SIZE], field[LINE_SIZE], type[LINE_SIZE], dummy[LINE_SIZE]; 

    /* Read each line */ 
    while(fgets(line, LINE_SIZE, fp)) 
    { 
    if(strchr(line,'\n')) *strchr(line,'\n')=0; 
    if(3==sscanf(line,"%[^: ]%[: ]%s,field,dummy,type)) 
     ++r,printf("\n %s [ %s ]",field,type); 
    } 
    return r; 
} 
1

如果你可以设计配置文件将是什么样子我会去XML,与Expat解析它。这是无痛的。

1

简单解析问题的标准答案是使用lex和yacc。

但是,由于您可以自由设置配置文件的形式,因此您应该使用实现各种配置文件格式的众多库中的一个,并使用该配置文件格式。

http://www.google.com/search?q=configuration+file+parser

http://www.nongnu.org/confuse/举例来说,似乎充分满足您的需求,但看看这可能是简单的,以及其他各种选项。

+0

谢谢,我会看看他们。同时你可以看到潜在的问题与我的源代码。 – ant2009 2010-11-20 12:21:25

+0

问题是C89,lex,yacc,...不是这个的一部分。 – user411313 2010-11-20 13:12:48