2010-11-20 278 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