gcc 4.5.1 c89
我正在使用以下代码从配置文件中读取一行文本。配置文件目前很小,会随着要添加的新字段而增长。我几乎可以自己设计配置文件的外观。所以我通过以下方式完成了它:
配置文件
# 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';
}