栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录

fstream读取txt

windows读取节点

 GxxPropertyUtils 读取key/value

在Windows的VC下


fstream读取txt

aaaa.h

void loadClassList(string m_classfile);
vector m_classNames;

aaaa.cpp

#include 
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 
namespace StringUtils {
	bool inline isBlank(char ch) {
		return ch == ' ' || ch == 't' || ch == 'r' || ch == 'n' || ch == '';
	}
	bool inline isBlank(wchar_t ch) {
		return ch == L' ' || ch == L't' || ch == L'r' || ch == L'n' || ch == '';
	}

}
namespace GxxPropertyUtils
{
	struct ConfigFile;
	
	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 
#include 
#include 
#include 
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 lines;
		map 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 )
	{
		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 )
	{
		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()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

[section]

key=string

   .

   .

获取integer

UINT GetPrivateProfileInt(

 LPCTSTR lpAppName, // section name

 LPCTSTR lpKeyName, // key name

 INT nDefault,    // return value if key name not found

 LPCTSTR lpFileName // initialization file name

);

注意:lpAppName和lpKeyName不区分大小写,当获得integer <0,那么返回0。lpFileName 必须是绝对路径,因相对路径是以C:windows

DWORD GetPrivateProfileString(

 LPCTSTR lpAppName,    // section name

 LPCTSTR lpKeyName,    // key name

 LPCTSTR lpDefault,    // default string

 LPTSTR lpReturnedString, // destination buffer

 DWORD nSize,       // size of destination buffer

 LPCTSTR lpFileName    // initialization file name

);

注意:lpAppName和lpKeyName不区分大小写,若lpAppName为NULL,lpReturnedString缓冲区内装载这个ini文件所有小节的列表,若为lpKeyName=NULL,就在lpReturnedString缓冲区内装载指定小节所有项的列表。lpFileName 必须是绝对路径,因相对路径是以C:windows,

返回值:复制到lpReturnedString缓冲区的字符数量,其中不包括那些NULL中止字符。如lpReturnedString缓冲区不够大,不能容下全部信息,就返回nSize-1(若lpAppName或lpKeyName为NULL,则返回nSize-2)

获取某一字段的所有keys和values

DWORD GetPrivateProfileSection(

 LPCTSTR lpAppName,    // section name

 LPTSTR lpReturnedString, // return buffer

 DWORD nSize,       // size of return buffer

 LPCTSTR lpFileName    // initialization file name

);

retrieves the names of all sections in an initialization file.

DWORD GetPrivateProfileSectionNames(

 LPTSTR lpszReturnBuffer, // return buffer

 DWORD nSize,       // size of return buffer

 LPCTSTR lpFileName    // initialization file name

);

其实就等于,GetPrivateProfileString(NULL,NULL,lpszReturnedBuffer,nSize,lpFileName)

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

  CString strCfgPath = _T("D:\test.ini"); //注意:'\'

  LPCTSTR lpszSection = _T("Font");

  int n = GetPrivateProfileInt(_T("FONT"), _T("size"), 9, strCfgPath);//n=12

  CString str;

  GetPrivateProfileString(lpszSection, _T("size"), _T("9pt"), str.GetBuffer(MAX_PATH), MAX_PATH, strCfgPath);

  str.ReleaseBuffer();//str="12pt"

  TCHAR buf[200] = { 0 };

  int nSize = sizeof(buf) / sizeof(buf[0]);

  GetPrivateProfileString(lpszSection, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "namesizecolor"

  memset(buf, 0, sizeof(buf));

  GetPrivateProfileString(NULL, _T("size"), _T(""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL

  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontLayoutBody"

  memset(buf, 0, sizeof(buf));

  GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);

  //buf: "name=宋体size=12ptcolor=RGB(255,0,0)"  此时“=”两边不会有空格

  memset(buf, 0, sizeof(buf));

  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontLayoutBody"

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

BOOL WritePrivateProfileString(

 LPCTSTR lpAppName, // section name

 LPCTSTR lpKeyName, // key name

 LPCTSTR lpString,  // string to add

 LPCTSTR lpFileName // initialization file

);

The WritePrivateProfileSection function replaces the keys and values for the specified section in an initialization file.

BOOL WritePrivateProfileSection(

 LPCTSTR lpAppName, // section name

 LPCTSTR lpString,  // data

 LPCTSTR lpFileName // file name

);

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.

例子:

1

2

3

4

5

6

7

WritePrivateProfileString(_T("Layout"), _T("left"), _T("100"), strCfgPath);

  WritePrivateProfileString(_T("Layout"), _T("top"), _T("80"), strCfgPath);

  //删除某Section,包括[Layout]和其下所有Keys=Value

  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);

  //删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]

  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

//而:WritePrivateProfileSection(NULL, NULL, strCfgPath);什么也不做,因Section为NULL

自己封装的函数:

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

map GetKeysValues(LPCTSTR szSection, LPCTSTR szIniFilePath)

获取ini文件的所有Section名

vector GetSectionsNames(LPCTSTR szIniFilePath)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

#include

#include

using std::vector;

using std::map;

//获取ini文件的所有Section名

vector GetSectionsNames(LPCTSTR szIniFilePath)

{

  vector vRet;

  TCHAR buf[2048] = { 0 };

  long nSize = sizeof(buf) / sizeof(buf[0]);

  ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  TCHAR *p, *q;

  p = q = buf;

  while (*p)//即 '' != *p

  {

    while (*q)

    {

      ++q;

    }

    CString str(p, q - p);

    vRet.push_back(str);

    p = q + 1;

    q = q + 1;

  }

  return vRet;

}

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

map GetKeysValues(LPCTSTR szSection, LPCTSTR szIniFilePath)

{

  map mapRet;

  TCHAR buf[2048] = { 0 };

  long nSize = sizeof(buf) / sizeof(buf[0]);

  GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

  TCHAR* p = buf;

  TCHAR* q = buf;

  while (*p)

  {

    CString strKey, strValue;

    while(*q)

    {

      if (_T('=') == *q)

      {

        strKey = CString(p, q - p);

        p = q + 1;

      }

      ++q;

    }

    strValue = CString(p, q - p);

    mapRet.insert(std::make_pair(strKey, strValue));

    p = q + 1;

    q = q + 1;

  }

  return mapRet;

}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960151.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号