c++ 操作配置文件学习笔记

x33g5p2x  于2022-06-10 转载在 其他  
字(19.1k)|赞(0)|评价(0)|浏览(334)

fstream读取txt

windows读取节点

GxxPropertyUtils 读取key/value

在Windows的VC下

fstream读取txt

aaaa.h

void loadClassList(string m_classfile);
vector<std::string> m_classNames;

aaaa.cpp

#include <fstream>
void Detector::loadClassList(string m_classfile)
{
	std::ifstream ifs(m_classfile);
	std::string line;
	while (getline(ifs, line))
		m_classNames.push_back(line);
}

windows读取节点

LPTSTR lpPath = new char[MAX_PATH];
 
strcpy(lpPath, "D:\\IniFileName.ini");
 
WritePrivateProfileString("LiMing", "Sex", "Man", lpPath);
WritePrivateProfileString("LiMing", "Age", "20", lpPath);
 
WritePrivateProfileString("Fangfang", "Sex", "Woman", lpPath);
WritePrivateProfileString("Fangfang", "Age", "21", lpPath);
 
delete [] lpPath;
 
//INI文件如下:
 
[LiMing]
Sex=Man
Age=20
[Fangfang]
Sex=Woman
Age=21
 
读INI文件:
 
LPTSTR lpPath = new char[MAX_PATH];
LPTSTR LiMingSex = new char[6];
int LiMingAge;
LPTSTR FangfangSex = new char[6];
int FangfangAge;
strcpy(lpPath, "..\\IniFileName.ini");
 
GetPrivateProfileString("LiMing", "Sex", "", LiMingSex, 6, lpPath);
LiMingAge = GetPrivateProfileInt("LiMing", "Age", 0, lpPath);
 
GetPrivateProfileString("Fangfang", "Sex", "", FangfangSex, 6, lpPath);
FangfangAge = GetPrivateProfileInt("Fangfang", "Age", 0, lpPath);

delete [] lpPath;

 GxxPropertyUtils 读取key/value

转自:C读取配置文件_guoxuxing的博客-CSDN博客_c 读取配置文件

调用示例:

123.conf

[LiMing]
#server ip port
server.ip=127.0.0.1
server.port = 8080

[test]

name=asdf

这个好像只能读取key,value,不能读节点 

#include "GxxPropertyUtils.h"
using namespace cv;

int main(int argc, char* argv[]) {

	GxxPropertyUtils::ConfigFile* cf = GxxPropertyUtils::OpenConfigFile("d:\\123.conf");

	std::string servIp = GxxPropertyUtils::GetPropertyString(cf, "server.ip");

	cout << servIp << endl;

	servIp = GxxPropertyUtils::GetPropertyString(cf, "server.port");

	cout << servIp << endl;

	GxxPropertyUtils::Close(cf);
}

GxxPropertyUtils.h

#pragma once
#include <string>
namespace StringUtils {
	bool inline isBlank(char ch) {
		return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\0';
	}
	bool inline isBlank(wchar_t ch) {
		return ch == L' ' || ch == L'\t' || ch == L'\r' || ch == L'\n' || ch == '\0';
	}

}
namespace GxxPropertyUtils
{
	struct ConfigFile;
	/**
	* 打开类似以下文件格式的配置文件
	* #server ip port
	* server.ip = 127.0.0.1
	* server.port = 8080
	*/
	ConfigFile* OpenConfigFile(const char* filepath, bool bReadonly = true);
	/**
	 * 保存配置
	 */
	void Save(ConfigFile* cf);
	/**
	 * 关闭配置, 如果配置有发生变化,则自动保存
	*/
	void Close(ConfigFile* cf);

	std::string GetPropertyString(ConfigFile* cf, const char* key, const char* defaultV = "");
	bool GetPropertyBool(ConfigFile* cf, const char* key, bool defaultV = false);
	int GetPropertyInteger(ConfigFile* cf, const char* key, int defaultV = 0);
	void WriteProperty(ConfigFile* cf, const char* key, const char* v);
	void WriteProperty(ConfigFile* cf, const char* key, bool v);
	void WriteProperty(ConfigFile* cf, const char* key, int v);
}

GxxPropertyUtils.cpp

#include "GxxPropertyUtils.h"
#include <fstream>
#include <vector>
#include <map>
#include <string>
using namespace std;

namespace GxxPropertyUtils {

	struct ConfigFileLine {
		short lineType; // 0:注释, 1:配置, 2:无效行
		string strLine;
		string strKey;
		string strValue;
	};
	struct ConfigFile {
		string filepath;
		bool readonly;
		bool modified;
		vector<ConfigFileLine> lines;
		map<string, int> mapV;
	};

	ConfigFile* OpenConfigFile(const char* filepath, bool bReadonly)
	{
		char buf[1025];
		int nLen;
		ConfigFile* pcf = new ConfigFile;
		try {
			pcf->filepath = filepath;
			pcf->readonly = bReadonly;
			pcf->modified = false;
			ifstream fd(filepath, ios_base::in | ios_base::_Nocreate);
			if (!fd.is_open())
				return pcf;
			while (!fd.eof()) {
				fd.getline(buf, 1024);
				nLen = strlen(buf);
				const char* pL = nullptr;
				const char* pLEnd = nullptr;
				const char* pR = nullptr;
				const char* p = buf;
				ConfigFileLine li;
				bool isComment = false;
				while (*p) {
					if (StringUtils::isBlank(*p)) {
						p++; continue;
					}
					if (*p == '#') {
						isComment = true; break;
					}
					pL = p;
					break;
				}
				if (isComment) {
					li.lineType = 0;
					li.strLine = buf;
					pcf->lines.push_back(li);
					continue;
				}
				if (pL == nullptr) {
					// 无效
					li.lineType = 2;
					li.strLine = buf;
					pcf->lines.push_back(li);
					continue;
				}
				while (*++p) {
					if (StringUtils::isBlank(*p) || *p == '=') {
						pLEnd = p;
						break;
					}
				}
				if (pLEnd == nullptr) {
					// 无效
					li.lineType = 2;
					li.strLine = buf;
					pcf->lines.push_back(li);
					continue;
				}
				while (*p) {
					if (*p == '=' || StringUtils::isBlank(*p)) {
						p++;
						continue;
					}
					pR = p;
					break;
				}
				if (pR == nullptr) {
					// 无效
					li.lineType = 2;
					li.strLine = buf;
					pcf->lines.push_back(li);
					continue;
				}
				p = buf + nLen;
				while (p != pR) {
					if (!StringUtils::isBlank(*p))
						break;
					--p;
				}
				li.lineType = 1;
				li.strLine = buf;
				li.strKey = string(pL, pLEnd - pL);
				li.strValue = string(pR, p - pR + 1);
				pcf->lines.push_back(li);
				pcf->mapV[li.strKey] = (int)pcf->lines.size() - 1;
			}
			fd.close();
		}
		catch (...) {
			delete pcf;
			return nullptr;
		}
		return pcf;
	}

	void Save(ConfigFile* cf)
	{
		if (!cf->readonly && cf->modified) {
			try {
				ofstream o(cf->filepath, ios_base::out);
				for (auto it = cf->lines.begin(); it != cf->lines.end(); ++it) {
					o << it->strLine << endl;
				}
				o.close();
			}
			catch (...) {

			}
		}
	}

	void Close(ConfigFile* cf)
	{
		Save(cf);

		delete cf;
	}

	std::string GetPropertyString(ConfigFile* cf, const char* key, const char* defaultV/*=""*/)
	{
		auto it = cf->mapV.find(string(key));
		if (it == cf->mapV.end())
			return string(defaultV);
		return cf->lines[it->second].strValue;
	}

	bool GetPropertyBool(ConfigFile* cf, const char* key, bool defaultV /*= false*/)
	{
		auto it = cf->mapV.find(string(key));
		if (it == cf->mapV.end())
			return defaultV;
		const string& v = cf->lines[it->second].strValue;
		if (v == "true")
			return true;
		return false;
	}

	int GetPropertyInteger(ConfigFile* cf, const char* key, int defaultV /*= 0*/)
	{
		auto it = cf->mapV.find(string(key));
		if (it == cf->mapV.end())
			return defaultV;
		const string& v = cf->lines[it->second].strValue;
		return atoi(v.c_str());
	}

	void WriteProperty(ConfigFile* cf, const char* key, const char* v)
	{
		string sKey(key);
		auto it = cf->mapV.find(sKey);
		if (it == cf->mapV.end()) {
			ConfigFileLine li;
			li.lineType = 1;
			li.strKey = key;
			li.strValue = (v == nullptr ? "" : v);
			li.strLine.append(li.strKey);
			li.strLine.append(" = ");
			li.strLine.append(li.strValue);
			cf->lines.push_back(li);
			cf->mapV[sKey] = cf->lines.size() - 1;
		}
		else {
			auto& li = cf->lines[it->second];
			li.strLine = li.strKey;
			li.strValue = (v == nullptr ? "" : v);
			li.strLine.append(" = ");
			li.strLine.append(li.strValue);
		}
		cf->modified = true;
	}

	void WriteProperty(ConfigFile* cf, const char* key, bool v)
	{
		WriteProperty(cf, key, v ? "true" : "false");
	}

	void WriteProperty(ConfigFile* cf, const char* key, int v)
	{
		char buf[12] = { 0 };
		_itoa_s(v, buf, 10);
		WriteProperty(cf, key, buf);
	}

}

在Windows的VC下

转自:https://www.jb51.net/article/192023.htm

读ini文件

例如:在D:\test.ini文件中
[Font]
name=宋体
size= 12pt
color = RGB(255,0,0)

上面的=号两边可以加空格,也可以不加

用GetPrivateProfileInt()和GetPrivateProfileString()

| <br>1<br><br>2<br><br>3<br><br>4<br><br>5<br><br>6<br><br>7<br><br>8<br><br>9<br><br>10<br><br>11<br><br>12<br><br>13<br><br>14<br><br>15<br><br>16<br><br>17<br><br>18<br><br>19<br><br>20<br><br>21<br><br>22<br><br>23<br><br>24<br><br>25<br><br>26<br><br>27<br><br>28<br><br>29<br><br>30<br><br>31<br><br>32<br><br>33<br><br>34<br><br>35<br><br>36<br><br>37<br><br>38<br><br>39<br><br>40<br><br>41<br><br>42<br> | <br>[section]<br><br>key=string<br><br>   ``.<br><br>   ``.<br><br>获取integer<br><br>UINT``GetPrivateProfileInt(<br><br> ``LPCTSTR``lpAppName,``// section name<br><br> ``LPCTSTR``lpKeyName,``// key name<br><br> ``INT``nDefault,   ``// return value if key name not found<br><br> ``LPCTSTR``lpFileName``// initialization file name<br><br>);<br><br>注意:lpAppName和lpKeyName不区分大小写,当获得integer <0,那么返回0。lpFileName 必须是绝对路径,因相对路径是以C:\windows\<br><br>DWORD``GetPrivateProfileString(<br><br> ``LPCTSTR``lpAppName,   ``// section name<br><br> ``LPCTSTR``lpKeyName,   ``// key name<br><br> ``LPCTSTR``lpDefault,   ``// default string<br><br> ``LPTSTR``lpReturnedString,``// destination buffer<br><br> ``DWORD``nSize,      ``// size of destination buffer<br><br> ``LPCTSTR``lpFileName   ``// initialization file name<br><br>);<br><br>注意:lpAppName和lpKeyName不区分大小写,若lpAppName为NULL,lpReturnedString缓冲区内装载这个ini文件所有小节的列表,若为lpKeyName=NULL,就在lpReturnedString缓冲区内装载指定小节所有项的列表。lpFileName 必须是绝对路径,因相对路径是以C:\windows\,<br><br>返回值:复制到lpReturnedString缓冲区的字符数量,其中不包括那些NULL中止字符。如lpReturnedString缓冲区不够大,不能容下全部信息,就返回nSize-1(若lpAppName或lpKeyName为NULL,则返回nSize-2)<br><br>获取某一字段的所有keys和values<br><br>DWORD``GetPrivateProfileSection(<br><br> ``LPCTSTR``lpAppName,   ``// section name<br><br> ``LPTSTR``lpReturnedString,``// return buffer<br><br> ``DWORD``nSize,      ``// size of return buffer<br><br> ``LPCTSTR``lpFileName   ``// initialization file name<br><br>);<br><br>retrieves the names of all sections in an initialization file.<br><br>DWORD``GetPrivateProfileSectionNames(<br><br> ``LPTSTR``lpszReturnBuffer,``// return buffer<br><br> ``DWORD``nSize,      ``// size of return buffer<br><br> ``LPCTSTR``lpFileName   ``// initialization file name<br><br>);<br><br>其实就等于,GetPrivateProfileString(NULL,NULL,lpszReturnedBuffer,nSize,lpFileName)<br> |

例子:

| <br>1<br><br>2<br><br>3<br><br>4<br><br>5<br><br>6<br><br>7<br><br>8<br><br>9<br><br>10<br><br>11<br><br>12<br><br>13<br><br>14<br><br>15<br><br>16<br><br>17<br><br>18<br><br>19<br><br>20<br><br>21<br><br>22<br><br>23<br><br>24<br><br>25<br><br>26<br><br>27<br><br>28<br><br>29<br><br>30<br><br>31<br><br>32<br><br>33<br> | <br>/* test.ini "="号两边可以加空格,也可以不加<br><br>  ``[Font]<br><br>  ``name=宋体<br><br>  ``size= 12pt<br><br>  ``color = RGB(255,0,0)<br><br>  ``[Layout]<br><br>  ``[Body]<br><br>  ``*/<br><br>  ``CString strCfgPath = _T(``"D:\\test.ini"``);``//注意:'\\'<br><br>  ``LPCTSTR``lpszSection = _T(``"Font"``);<br><br>  ``int``n = GetPrivateProfileInt(_T(``"FONT"``), _T(``"size"``), 9, strCfgPath);``//n=12<br><br>  ``CString str;<br><br>  ``GetPrivateProfileString(lpszSection, _T(``"size"``), _T(``"9pt"``), str.GetBuffer(MAX_PATH), MAX_PATH, strCfgPath);<br><br>  ``str.ReleaseBuffer();``//str="12pt"<br><br>  ``TCHAR``buf[200] = { 0 };<br><br>  ``int``nSize =``sizeof``(buf) /``sizeof``(buf[0]);<br><br>  ``GetPrivateProfileString(lpszSection, NULL, _T(``""``), buf, nSize, strCfgPath);<br><br>  ``//buf: "name\0size\0color\0\0"<br><br>  ``memset``(buf, 0,``sizeof``(buf));<br><br>  ``GetPrivateProfileString(NULL, _T(``"size"``), _T(``""``), buf, nSize, strCfgPath);``//没Section,_T("size")没意义了,所以可以写NULL<br><br>  ``//可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);<br><br>  ``//buf: "Font\0Layout\0Body\0\0"<br><br>  ``memset``(buf, 0,``sizeof``(buf));<br><br>  ``GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);<br><br>  ``//buf: "name=宋体\0size=12pt\0color=RGB(255,0,0)\0\0"  此时“=”两边不会有空格<br><br>  ``memset``(buf, 0,``sizeof``(buf));<br><br>  ``GetPrivateProfileSectionNames(buf, nSize, strCfgPath);``//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);<br><br>  ``//buf: "Font\0Layout\0Body\0\0"<br> |

写ini文件

WritePrivateProfileString函数,没有写integer的,可以转成string再写入。

| <br>1<br><br>2<br><br>3<br><br>4<br><br>5<br><br>6<br><br>7<br><br>8<br><br>9<br><br>10<br><br>11<br><br>12<br><br>13<br><br>14<br> | <br>BOOL``WritePrivateProfileString(<br><br> ``LPCTSTR``lpAppName,``// section name<br><br> ``LPCTSTR``lpKeyName,``// key name<br><br> ``LPCTSTR``lpString, ``// string to add<br><br> ``LPCTSTR``lpFileName``// initialization file<br><br>);<br><br>The WritePrivateProfileSection function replaces the keys and values``for``the specified section in an initialization file.<br><br>BOOL``WritePrivateProfileSection(<br><br> ``LPCTSTR``lpAppName,``// section name<br><br> ``LPCTSTR``lpString, ``// data<br><br> ``LPCTSTR``lpFileName``// file name<br><br>);<br> |

WritePrivateProfileString:

Remarks
If the lpFileName parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If lpFileName contains a full path and file name and the file does not exist, WritePrivateProfileString creates the file. The specified directory must already exist.

WritePrivateProfileSection:

Remarks
The data in the buffer pointed to by the lpString parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WritePrivateProfileSection function is not case-sensitive; the string pointed to by the lpAppName parameter can be a combination of uppercase and lowercase letters.

If no section name matches the string pointed to by the lpAppName parameter, WritePrivateProfileSection creates the section at the end of the specified initialization file and initializes the new section with the specified key name and value pairs.

WritePrivateProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by the lpString parameter. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no operations that read from or write to the specified initialization file are allowed while the information is being written.

例子:

| <br>1<br><br>2<br><br>3<br><br>4<br><br>5<br><br>6<br><br>7<br> | <br>WritePrivateProfileString(_T(``"Layout"``), _T(``"left"``), _T(``"100"``), strCfgPath);<br><br>  ``WritePrivateProfileString(_T(``"Layout"``), _T(``"top"``), _T(``"80"``), strCfgPath);<br><br>  ``//``删除某Section,包括[Layout]和其下所有Keys=Value<br><br>  ``WritePrivateProfileSection(_T(``"Layout"``), NULL, strCfgPath);<br><br>  ``//``删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]<br><br>  ``WritePrivateProfileSection(_T(``"Layout"``), _T(``""``), strCfgPath);<br><br>//``而:WritePrivateProfileSection(NULL, NULL, strCfgPath);什么也不做,因Section为NULL<br> |

自己封装的函数:

获取某一个Section的所有 key=value

map<CString, CString> GetKeysValues(LPCTSTR szSection, LPCTSTR szIniFilePath)

获取ini文件的所有Section名

vector<CString> GetSectionsNames(LPCTSTR szIniFilePath)

| <br>1<br><br>2<br><br>3<br><br>4<br><br>5<br><br>6<br><br>7<br><br>8<br><br>9<br><br>10<br><br>11<br><br>12<br><br>13<br><br>14<br><br>15<br><br>16<br><br>17<br><br>18<br><br>19<br><br>20<br><br>21<br><br>22<br><br>23<br><br>24<br><br>25<br><br>26<br><br>27<br><br>28<br><br>29<br><br>30<br><br>31<br><br>32<br><br>33<br><br>34<br><br>35<br><br>36<br><br>37<br><br>38<br><br>39<br><br>40<br><br>41<br><br>42<br><br>43<br><br>44<br><br>45<br><br>46<br><br>47<br><br>48<br><br>49<br><br>50<br><br>51<br><br>52<br><br>53<br><br>54<br> | <br>#include <vector><br><br>#include <map><br><br>using``std::vector;<br><br>using``std::map;<br><br>//获取ini文件的所有Section名<br><br>vector<CString> GetSectionsNames(``LPCTSTR``szIniFilePath)<br><br>{<br><br>  ``vector<CString> vRet;<br><br>  ``TCHAR``buf[2048] = { 0 };<br><br>  ``long``nSize =``sizeof``(buf) /``sizeof``(buf[0]);<br><br>  ``::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);<br><br>  ``TCHAR``*p, *q;<br><br>  ``p = q = buf;<br><br>  ``while``(*p)``//即 '\0' != *p<br><br>  ``{<br><br>    ``while``(*q)<br><br>    ``{<br><br>      ``++q;<br><br>    ``}<br><br>    ``CString str(p, q - p);<br><br>    ``vRet.push_back(str);<br><br>    ``p = q + 1;<br><br>    ``q = q + 1;<br><br>  ``}<br><br>  ``return``vRet;<br><br>}<br><br>//获取某一个Section的所有 key=value<br><br>map<CString, CString> GetKeysValues(``LPCTSTR``szSection,``LPCTSTR``szIniFilePath)<br><br>{<br><br>  ``map<CString,CString> mapRet;<br><br>  ``TCHAR``buf[2048] = { 0 };<br><br>  ``long``nSize =``sizeof``(buf) /``sizeof``(buf[0]);<br><br>  ``GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);<br><br>  ``TCHAR``* p = buf;<br><br>  ``TCHAR``* q = buf;<br><br>  ``while``(*p)<br><br>  ``{<br><br>    ``CString strKey, strValue;<br><br>    ``while``(*q)<br><br>    ``{<br><br>      ``if``(_T(``'='``) == *q)<br><br>      ``{<br><br>        ``strKey = CString(p, q - p);<br><br>        ``p = q + 1;<br><br>      ``}<br><br>      ``++q;<br><br>    ``}<br><br>    ``strValue = CString(p, q - p);<br><br>    ``mapRet.insert(std::make_pair(strKey, strValue));<br><br>    ``p = q + 1;<br><br>    ``q = q + 1;<br><br>  ``}<br><br>  ``return``mapRet;<br><br>}<br> |

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

微信公众号

最新文章

更多