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';
}
問題是C89,正則表達式是不是這項工作的一部分。 – user411313 2010-11-20 13:11:37