2011-09-12 63 views
0

我是C++和boost中的新手。我正在尝试使用boost :: program_options读取(稍后写入)INI文件。我甚至尝试使用boost :: property_tree。无法读取INI文件使用boost :: program_options解析

两个(program_options & property_tree)在使用std :: stringstream s(“[test] \ n”“a = 2 \ n”“b = 3 \ n”)时是完美的,但是当std :: ifstream s(“dimension.ini”)。我已经把文件:dimension.ini,Rcasdim.hpp/cpp放在同一个文件夹中,并且在搜索目录中也有相关的boost lib文件。

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; 
} 

回答

1

您不需要将ini文件和hpp/cpp文件放在同一个文件夹中。
dimension.ini文件与您的二进制文件(Windows上的linux.exe上的可执行文件)在同一文件夹中。
位置取决于您的构建系统和平台,最有可能的是我忘记的一些事情。

+0

thnx for reply..why是boost :: program_options无法从我的程序中的“dimension.ini”中读取/检测“Key = Value”? érror在哪里? – boosturself

+1

'std :: ifstream s(“dimension.ini”)'这行说从当前工作目录加载文件dimensions.ini。您需要指定路径或在运行时确定它。它与提升无关。 – mkaes

+0

问题在于传递文件名。在property_tree控制程序之前,文件名(文件)应该可以打开。简单地说,对于这个“文件”,执行“this”(这里是对INI文件的property_tree解析) – boosturself