开发者

Unable to read INI file Parsing using boost::program_options

开发者 https://www.devze.com 2023-04-04 12:36 出处:网络
I am a newbie in c++ and boost. I am attempting to read (later write) to INI file using boost::program_options. I even tried using boost::property_tree.

I am a newbie in c++ and boost. I am attempting to read (later write) to INI file using boost::program_options. I even tried using boost::property_tree.

Both(program_options & property_tree) work perfectly when std::stringstream s("[test]\n""a=2\n""b=3\n") is used, BUT NOT when std::ifstream s("dimension.ini"). I have put files: dimension.ini, Rcasdim.hpp/cpp in the same folder, and also have relevant boost l开发者_运维技巧ib files in search directory.

INI File

[Section]

a=2

b=3

Purpose:  
I need to dynamically set the "Value" (at the start ONLY) for a Particular "Key" in INI file & Later USE that Previously set "Value" for that "Key" by other project files (more, as a toggle)

 #include boost/program_options/detail/config_file.hpp

 #include boost/program_options/parsers.hpp


namespace pod = boost::program_options::detail;

class CRcasdim
{
    public:
    CRcasdim(){};
    ~CRcasdim(){};
    std::string getrcasdim(float);

    private:
    std::string sd;
};

std::string CRcasdim::getrcasdim(float d)

{

    //std::stringstream s("[Section]\n""a=2\n""b=3\n"); WORKS

    std::ifstream s("dimension.ini"); DOESNT WORK

    if(!s)
    {
        std::cerr<<"error"<<std::endl;
    }

    std::set<std::string> options;
    std::map<std::string, std::string> parameters;

    options.insert("Section.a");
    options.insert("Section.b");

try

{

    for (pod::config_file_iterator i(s, options), e ; i != e; ++i)

        parameters[i->string_key] = i->value[0];   
}

catch(std::exception& e)

{
std::cerr<<"Exception: ";
}

    if (d==2)
    sd = parameters["Section.a"];

    else if (d==3)
    sd = parameters["Section.b"];

    return sd;
}


You don't need to put the ini file and the hpp/cpp files in the same folder.
The dimension.ini file has be in the same folder like your binary(executable on linux .exe on windows).
The location depends on your build system and your platform and most probably some things I forgot.

0

精彩评论

暂无评论...
验证码 换一张
取 消