在C ++中创建一个简单的配置文件和解析器 [英] Creating a simple configuration file and parser in C++
问题描述
我正在尝试创建一个像这样的简单配置文件
I am trying to create a simple configuration file that looks like this
url = http://mysite.com
file = main.exe
true = 0
希望将配置设置加载到下面列出的程序变量中。
when the program runs, I would like it to load the configuration settings into the programs variables listed below.
string url, file;
bool true_false;
我做了一些研究,这链接似乎有帮助(nucleon的帖子),但我似乎不能得到它的工作,它是太复杂,我不能理解。有一个简单的方法这样做吗?我可以使用 ifstream
加载文件,但这是我自己可以得到的。谢谢!
I have done some research and this link seemed to help (nucleon's post) but I can't seem to get it to work and it is too complicated to understand on my part. Is there a simple way of doing this? I can load the file using ifstream
but that is as far as I can get on my own. Thanks!
推荐答案
一般来说,最简单的方法是在两个阶段解析这些典型的配置文件:首先读取行,然后解析
在C ++中,可以使用 std :: getline()
从流中读取行。默认情况下,它会读到下一个'\\\
(它将消耗,但不返回),你也可以传递一些其他分隔符,使得它成为一个很好的候选人阅读up-to-some-char,如
' =
在你的例子中。
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline()
. While by default it will read up to the next '\n'
(which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like =
in your example.
为简单起见,以下假设 =
不是由空白包围的 。如果你想在这些位置允许空格,你将战略性地放置是>> std :: ws
,然后从键中删除结尾空格。但是,IMO在语法上增加一点灵活性是不值得配置文件读取器的麻烦。
For simplicity, the following presumes that the =
are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws
before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.
const char config[] = "url=http://example.com\n"
"file=main.exe\n"
"true=0";
std::istringstream is_file(config);
std::string line;
while( std::getline(is_file, line) )
{
std::istringstream is_line(line);
std::string key;
if( std::getline(is_line, key, '=') )
{
std::string value;
if( std::getline(is_line, value) )
store_line(key, value);
}
}
锻炼给读者。)
这篇关于在C ++中创建一个简单的配置文件和解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!