【C/C++】解析简单配置文件|解析从脚本读出的流配置

本文详细介绍了如何使用C++解析name=value格式的配置文件,包括去除空格、按分隔符拆分字符串的实现细节,并提到了从脚本读取配置的 GNU getline 函数。
摘要由CSDN通过智能技术生成

目录

解析简单配置文件 std::getline

配置文件的格式

实施摘要

实现细节 1 - 去除空格

Implementation detail 2 - Splitting a string at the delimiter

执行脚本并从脚本中读出配置 GNU getline


解析简单配置文件 std::getline

本文解释了如何解析类似于 Windows .ini 文件的 name=value 形式的配置文件。该代码从行中删除所有空格并跳过空行和包含注释的行。

配置文件的格式

The code explained in this article can parse both a formatted and unformatted input

# formatted
generates_output=true
file_format=txt
# unformatted
generates_output  =  false
  file_format=doc

实施摘要

下面的代码解析配置文件。在我们成功加载文件后,我们一行一行地读取它。我们从该行中删除所有空格,如果该行为空或包含注释(用“#”表示),则跳过该行。之后,我们在分隔符“=”处拆分字符串“name=value”并打印名称和值。

#include <iostream>
#include <fstream>
#include <algorithm>

int main()
{
    // std::ifstream is RAII, i.e. no need to call close
    std::ifstream cFile ("config2.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);
            std::cout << name << " " << value << '\n';
        }
        
    }
    else {
        std::cerr << "Couldn't open config file for reading.\n&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值