解析一个非常简单的配置文件

Parsing a Very Simply Config File

本文关键字:非常 简单 配置文件 一个      更新时间:2023-10-16

我正在用c++编写一个OBDII阅读库/应用程序。通过发送一个简单的字符串命令从汽车的计算机中检索数据,然后将结果传递给特定于每个参数的函数。

我想读取所有我想要的命令的配置文件,像这样的东西:

Name, Command, function
Engine RPM, 010C, ((256*A)+B)/4
Speed, 010D, A

基本上,非常简单,所有的数据都需要作为字符串读入。有人能推荐一个简单的库吗?我的目标是g++和/或Linux上的Clang。

您可以使用std::ifstream逐行读取,并使用boost::split,分割行。

示例代码:

您可以检查令牌大小以检查所加载文件的完整性。

#include <fstream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
int main(int argc, char* argv[]) {
    std::ifstream ifs("e:\save.txt");
    std::string line;
    std::vector<std::string> tokens;
    while (std::getline(ifs, line)) {
        boost::split(tokens, line, boost::is_any_of(","));
        if (line.empty())
            continue;
        for (const auto& t : tokens) {
            std::cout << t << std::endl;
        }
    }
    return 0;
}

如果你不想实现,你也可以使用String Toolkit Library。文档