使用boost::property_tree::ptree编写ini文件注释

6

有没有办法使用boost::property::ptree在ini文件中编写注释?

就像这样:

  void save_ini(const std::string& path)
  {
      boost::property_tree::ptree pt;
      int first_value = 1;
      int second_value = 2;
      
      // Write a comment to describe what the first_value is here
      pt.put("something.first_value", );
      // Write a second comment here
      pt.put("something.second_value", second_value);

      boost::property_tree::write_ini(path, pt);
  }

这里的文档没有提供相关信息。Boost是否实现了该功能?

2个回答

6

boost::property_tree::ptree用于各种“属性树”类型(INFO、INI、XML、JSON等),因此它本身并不支持除允许键=值设置外的任何其他操作。您的最终行(应为):

boost::property_tree::ini_parser::write_ini(path, pt);

这里唯一定义了你所做的事情是INI格式,而不是其他格式。例如,你可以轻松地将该行替换为写入XML,它也可以工作。因此,你可以看到property_tree::ptree不能具有特定于特定类型文件的内容。


你能做的最好的事情就是为每个子元素添加一个“注释”设置,例如:

pt.put("something.comments", "Here are the comments for the 'something' section");

您可以为任何名称的子元素设置属性...在读取期间迭代时,只需忽略它们即可。因此,如果您愿意,没有理由不这样创造性地使用 -- 这是您的程序!


4
我考虑过,但我觉得我会选择不加评论而离开它。我宁愿这样做,也不要有含有评论的虚假属性。无论如何,谢谢! - Jeff Bencteux
我认为它不会正常工作 - 不能保证写入指令的顺序符合您的要求。 - agodinhost

0
using boost::property_tree::ptree;
ptree pt;
// first way
pt.put("a.;Below value is of float type", ">");
pt.put("a.value", 2.72f);**

//second way
pt.put("a.;The value of bvalue is used to show how to write comments in ini 
file:\nbvalue", 3.14f);
write_ini(filename, pt);

输出.ini文件的内容:

[a]
;Below value is of float type=>
value=2.72000003
;The value of bvalue is used to show how to write comments in ini file:
bvalue=3.1400001

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接