Introduction: it is common to read configuration files, especially when the backend server (Linux or UNIX) runs programs for scalability. configuration files are often used as program input to complete different work content. This article provides a simple implementation method:
Let's not talk much about it. Look at the function:
/** Parameter: the absolute path name of the parameter filepath file, for example,/user/home/My. the variable name * value in the CFG * key text corresponds to the value of the variable, used to save **/# include <iostream> # include <string> # include <fstream> static bool readconfigfile (const char * character filepath, const string & Key, string & value) {fstream Upload File; Specify file. open (export filepath); // open the file if (! Export File. is_open () {cout <"can not open cfg file! "<Endl; return false;} Char TMP [1000]; while (! Invalid file. EOF () // read each row in a loop {folder file. getline (TMP, 1000); // read the first 1000 characters in each line. The first 1000 characters should be enough for string line (TMP); size_t Pos = line. find ('='); // locate the "=" position of each line, followed by the key and the value if (Pos = string: NPOs) return false; string tmpkey = line. substr (0, POS); // obtain if (Key = tmpkey) {value = line. substr (Pos + 1); // return true after =;} return false ;}
The variable content of a text file should be in the following format:
Id = 20
Name = Bob
Address = Beijing