用 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 '
'
(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.
为简单起见,以下假设 =
not 被空格包围.如果你想在这些位置允许空格,你必须有策略地放置 is >>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
"
"file=main.exe
"
"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);
}
}
(添加错误处理留给读者作为练习.)
相关文章