Creating a simple configuration file and parser in C++

前端 未结 12 724
谎友^
谎友^ 2020-12-07 10:55

I am trying to create a simple configuration file that looks like this

url = http://mysite.com
file = main.exe
true = 0

when the program ru

12条回答
  •  死守一世寂寞
    2020-12-07 11:49

    I was searching for a similar simple C++ config file parser and this tutorial website provided me with a basic yet working solution. Its quick and dirty soultion to get the job done.

    myConfig.txt
    
    gamma=2.8
    mode  =  1
    path = D:\Photoshop\Projects\Workspace\Images\
    

    The following program reads the previous configuration file:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        double gamma = 0;
        int mode = 0;
        std::string path;
    
        // std::ifstream is RAII, i.e. no need to call close
        std::ifstream cFile("myConfig.txt");
        if (cFile.is_open())
        {
            std::string line;
            while (getline(cFile, line)) 
            {
                line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
                if (line[0] == '#' || line.empty()) continue;
    
                auto delimiterPos = line.find("=");
                auto name = line.substr(0, delimiterPos);
                auto value = line.substr(delimiterPos + 1);
    
                //Custom coding
                if (name == "gamma") gamma = std::stod(value);
                else if (name == "mode") mode = std::stoi(value);
                else if (name == "path") path = value;
            }
        }
        else 
        {
            std::cerr << "Couldn't open config file for reading.\n";
        }
    
        std::cout << "\nGamma=" << gamma;
        std::cout << "\nMode=" << mode;
        std::cout << "\nPath=" << path;
        std::getchar();
    }
    

提交回复
热议问题