1.11M Members

How do I make a config file ?

 
0
 

The title says it all i want to make 1 file which can store information which my C++ program can read and use. How do I go about doing this.

 
0
 

All a config file need be is a simple text file with the values stored in it that your program will use.

The program will open the file, read and heed the values. If the user wants to change those values through the program, then it will have to also write the changes to the file.

Beyond that, it contains whatever you want or need.

 
0
 

how do i for instance say goto line 1 of the config file or go to line 50

 
0
 

you could simply read through the file, line by line, not doing anything with the data you don't need at the moment.

If your file is formatted with every line exactly the same length, you could perhaps use the seekg( ) method to jump around to where a given line begins.

 
0
 

You could even use xml file for your configs . In my opinion its a bit easier than searching directly from text files.

 
0
 

But how do i search line by line how does my program differ 1 line from another

 
0
 

Imagine the next example:
You have a config.txt and in it u have :
@hdd=1024#
@ram=512#
You could use regex , and find the name of the variable thats betwen @ and = and the value of that variable that is betwen = and #.

 
0
 

Imagine the next example:
You have a config.txt and in it u have :
@hdd=1024#
@ram=512#
You could use regex , and find the name of the variable thats betwen @ and = and the value of that variable that is betwen = and #.

Whats regex

 
0
 

BUMP

 
1
 

You shouldn't really "BUMP" a post. At least pretend to ask another question!

regex is something you can look up yourself, but it is not necessary for your problem. Here's an example of parsing a simple config file:

/* File config.txt:
num = 123
str = hello
flt = 12.2
*/

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

struct Config {
    int    num;
    string str;
    double flt;
};

void loadConfig(Config& config) {
    ifstream fin("config.txt");
    string line;
    while (getline(fin, line)) {
        istringstream sin(line.substr(line.find("=") + 1));
        if (line.find("num") != -1)
            sin >> config.num;
        else if (line.find("str") != -1)
            sin >> config.str;
        else if (line.find("flt") != -1)
            sin >> config.flt;
    }
}

int main() {
    Config config;
    loadConfig(config);
    cout << config.num << '\n';
    cout << config.str << '\n';
    cout << config.flt << '\n';
}
 
0
 

Thanks +rep

Question Answered as of 5 Years Ago by vmanes, jen140 and nucleon
 
0
 

Soz for upping such and old post .
But regex is -> regular expression , try searching it on google.

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article