C/C ++: simple implementation of reading configuration file (text) Content

Source: Internet
Author: User

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
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.