5

I am trying to parse an Ini-file (using boost) and write some changed values back to the file. A simple example for this is the following code (main.cpp):

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
#include <exception>

int main()
{
    try
    {
        boost::property_tree::ptree pt;
        boost::property_tree::ini_parser::read_ini("testini.ini", pt);

        int i = pt.get<int>("Section1.Value1");

        std::cout << i << std::endl;

        pt.put("Section1.Value1", 32);

        boost::property_tree::ini_parser::write_ini( "testini.ini", pt );
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    } 
    return 0;
}

With this, I am accessing the following ini file (testini.ini):

[Section1]
; Test variable
Value1=1

This works quite well, however, the comment is not preserved and the newly written file looks like this

[Section1]
Value1=32

and what I wanted is

[Section1]
; Test variable
Value1=32

Now the question is, is there a way to preserve the comment in the file? It must not need to use the ini-parser!

  • 1
    I tried running the code referenced there and it does not work, it did still overwrite my comments :( So I am not sure it is duplicate. Did you check if it is working? –  Jul 31 '17 at 11:54
  • yes sorry, it probably couldn't help you. I am afraid you are unable to achieve what you want, unless you choose solution like this https://stackoverflow.com/questions/27354838/writing-comments-to-ini-file-with-boostproperty-treeptree?rq=1 – vasek Jul 31 '17 at 11:58
  • Yeah, I found this as well, but as far as I understand it, it cannot be used to preserve comments edited manually to the ini-file. However, this is often the case for me. –  Jul 31 '17 at 12:03
  • 1
    See also this https://stackoverflow.com/questions/26341556/boost-property-tree-ini-parsing-gives-error-if-any-comment-is-appended-to-key-va – vasek Jul 31 '17 at 12:11
  • Looks like a different problem to me, but I may be mistaken. –  Jul 31 '17 at 13:43
  • 1
    It's impossible using boost because ini parser ignores comments, see [this](https://github.com/boostorg/property_tree/blob/develop/include/boost/property_tree/ini_parser.hpp#L99). – vasek Jul 31 '17 at 14:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150630/discussion-between-andi-and-vasek). –  Jul 31 '17 at 14:27
  • 1
    @vasek it's not impossible using boost, but it is not a feature of Boost PropertyTree – sehe Jul 31 '17 at 20:33

0 Answers0