c++快速读取配置文件

472 阅读1分钟

配置文件样例

#in.txt #缩放到1280 720 rtsp://127.0.0.1/l.264 1280 720

#开头代表注释,而一行中有三个数据,以空格隔开。分别是rtsp地址,宽度 ,高度。使用c++ fstream的移位符来读取空格后数据。

srcFile >> s.d_width >> s.d_height;

读取文件

std::ifstream srcFile("in.txt", std::ios::in); //以文本模式打开in.txt备读

show me the code

#include <iostream>
#include <fstream>
#include <cstdlib> 
#include <vector>
#include <string>
typedef struct s_source
{
	std::string v_s;
	int d_width;
	int d_height;
}s_source;
class c_file
{
	std::vector<s_source> v_sources;
public:
	int func_read()
	{
		std::ifstream srcFile("in.txt", std::ios::in); //以文本模式打开in.txt备读
		if (!srcFile) { //打开失败
			std::cout << "error opening source file." << std::endl;
			return -1;
		}

		while (!srcFile.bad()) {
			s_source s;
			srcFile >> s.v_s;
			if (s.v_s[0] != '#')
			{
				srcFile >> s.d_width >> s.d_height;
				v_sources.push_back(s);
			}
		}

		for (auto x : v_sources)
		{
			std::cout << x.v_s << " " << x.d_width << " " << x.d_height << std::endl;
		}
		return 0;
	}
};

读取测试

读者也可以修改方式为传文件名参数,这是个简单的方式,可以做扩展。

int main(int argc, char* argv[])
{
	/* 这个要更新*/
	c_file f;
	if (f.func_read() != 0)
		return -1;
	return 0;
}