2011-04-18 60 views
2

我在哪裏可以找到用於讀取和操作Unix配置文件的C或C++庫(format: name=value\n)?C/C++ Unix配置文件庫

+0

C(或C++)標準庫? – pmg 2011-04-18 08:50:24

+0

我確定有人會提到C++的'boost :: program_options'和C的'getopt'。 – Nim 2011-04-18 08:50:51

+0

對不起,這可能聽起來像一個愚蠢的問題,我對C/C++非常陌生。 – Spliffster 2011-04-18 08:51:32

回答

2

對於純C,libconfuse相當不錯

+0

有趣,看起來與puppet使用的格式類似。 – Spliffster 2014-10-04 17:58:03

6

我會建議你使用C++的boost :: property_tree庫。它有安靜的詳細手冊。此外,我會建議你使用「信息」配置文件。配置文件的

例子:

; this is just comment line 

firstParamSection 
{ 
    stringParam "string" 
    intParam 10 
} 

的代碼示例來檢索配置文件中這個參數:

#include <boost/property_tree/ptree.hpp> 
#include <boost/property_tree/info_parser.hpp> 
#include <string> 

int main (int argc, char *argv[]) { 
    std::string testString; 
    int testInt; 

    boost::property_tree::ptree pTree; 
    try { 
    read_info("test/config/file/name", pTree); 
    } 
    catch (boost::property_tree::info_parser_error e) { 
    std::cout << "error" << std::endl; 
    } 

    try { 
    testString = pTree.get<std::string>("firstParamSection.stringParam"); 
    testInt = pTree.get<int>("firstParamSection.intParam"); 
    } 

    catch(boost::property_tree::ptree_bad_path e) { 
    std::cout << "error" << std::endl; 
    } 
+0

如果你想使用strcitly(name =「value」)格式,boost也支持它。只需使用ini_parser而不是info_parser。 – beduin 2011-04-18 10:16:55

+0

這似乎是我正在尋找的解決方案。然而,我認爲我將首先推出自己的解決方案(用於教育目的),然後在以後的項目中轉向提升。謝謝! – Spliffster 2011-04-18 10:20:08

1

我已經寫了一個配置解析器「信息」的風格配置文件我自己几几周前。這是完全符合XDG,可以嵌套,它是很容易使用:

// read config file "barc" in directory $XDG_CONFIG_HOME/foo, e.g. /home/bwk/.config/foo/barc 
config_read("foo", "barc"); 

// can read a specific file as well: 
config_read_file("/etc/tralalarc"); 

// or from an open FILE *fp 
config_read_fp(fp); 

// or n characters directly from memory 
config_read_mem(0xDEADBEEF, n); 


// retrieve value associated with "key" in section "here", sub-section "my" 
char *val = config_get("here.my.key"); 

您還可以設置/鎖配置變量,包括評論,寫配置回磁盤。這很自我解釋,但它缺乏文檔。見config.*here

我很樂意根據需要添加文檔和/或界面。

+0

感謝您的示例代碼。因爲我只有幾天進入C這將幫助我理解文件和字符串處理。 – Spliffster 2011-04-18 10:21:38