linux c语言 readline,Linux C代码实现读取配置文件示例
/**
讀配置文件示例
注:配置文件必須為unix格式,即\n結(jié)尾
*/
#include
#include
#include
#include
#include
// 結(jié)構(gòu)體
struct hostapd_config
{
char iface[16];
uint16_t beacon_int;
uint8_t channel;
char country[3]; /* first two octets: country code as described in
* ISO/IEC 3166-1. Third octet:
* ' ' (ascii 32): all environments
* 'O': Outdoor environemnt only
* 'I': Indoor environment only
*/
};
// 默認值
struct hostapd_config * config_defaults(void)
{
struct hostapd_config *conf = NULL;
conf = (struct hostapd_config *)calloc(1, sizeof(*conf));
if (conf == NULL)
{
return NULL;
}
// set default value
conf->beacon_int = 100;
conf->channel = 1;
return conf;
}
// 根據(jù)讀取到的信息填充結(jié)構(gòu)體
static int config_defaults(struct hostapd_config *conf, const char *buf, char *pos, int line)
{
if (strcmp(buf, "interface") == 0)
{
strncpy(conf->iface, pos, sizeof(conf->iface));
}
else if (strcmp(buf, "channel") == 0)
{
int val = atoi(pos);
conf->channel = val;
}
else if (strcmp(buf, "beacon_int") == 0)
{
int val = atoi(pos);
conf->beacon_int = val;
}
else if (strcmp(buf, "country_code") == 0)
{
memcpy(conf->country, pos, 2);
conf->country[2] = ' ';
}
// more ...
return 0;
}
//
// 讀配置文件
struct hostapd_config* config_read(const char *fname)
{
struct hostapd_config *conf = NULL;
FILE *f = NULL;
char buf[1024] = {0};
char *pos = NULL;
int line = 0;
int errors = 0;
f = fopen(fname, "r");
if (f == NULL)
{
printf("Could not open configuration file '%s' for reading.\n", fname);
return NULL;
}
conf = config_defaults();
if (conf == NULL)
{
fclose(f);
return NULL;
}
while (fgets(buf, sizeof(buf), f))
{
line++;
if (buf[0] == '#')
continue;
pos = buf;
while (*pos != '\0')
{
if (*pos == '\n')
{
*pos = '\0';
break;
}
pos++;
}
if (buf[0] == '\0')
continue;
pos = strchr(buf, '=');
if (pos == NULL) {
printf("Line %d: invalid line '%s'\n", line, buf);
errors++;
continue;
}
*pos = '\0';
pos++;
errors += config_defaults(conf, buf, pos, line);
}
fclose(f);
return conf;
}
/
int main(int argc, char *argv[])
{
const char* conf_file = "foo.conf";
if (argc == 2)
{
conf_file = argv[1];
}
struct hostapd_config *conf = NULL;
conf = config_read(conf_file);
if (conf == NULL)
{
printf("failed to read file: %s\n", conf_file);
return -1;
}
printf("%d %s %s\n", conf->channel, conf->country, conf->iface);
return 0;
}
總結(jié)
以上是生活随笔為你收集整理的linux c语言 readline,Linux C代码实现读取配置文件示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux搭建环境经验,经验总结54--
- 下一篇: linux可以ping通,Linux可以