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.

Recommended Answers

All 11 Replies

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.

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

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.

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

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

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 #.

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

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

Thanks +rep

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.