Error[8]: Undefined offset: 377, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}[+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 378, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 379, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 380, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 381, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 382, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 383, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 384, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 385, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 386, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 387, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 388, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 389, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 390, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++][+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 391, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++] [+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 392, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 393, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

[+++]

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
c++ *** 作配置文件学习笔记_C_内存溢出

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

c++  *** 作配置文件学习笔记,第1张

目录

fstream读取txt

class="superseo">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 == '\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 
#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 /*= 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()

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

/* test.ini "="号两边可以加空格,也可以不加

  [Font]

  name=宋体

  size= 12pt

  color = RGB(255,0,0)

  [Layout]

  [Body]

  */

  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: "name  sizememsetcolor(buf, 0, sizeof"

(buf));  GetPrivateProfileString(NULL, _T("size"), _T(

""), buf, nSize, strCfgPath);//没Section,_T("size")没意义了,所以可以写NULL  //可以是 GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);  //buf: "Font  LayoutmemsetBody(buf, 0, sizeof"

(buf));  

GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);  

//buf: "name=宋体  size=12ptmemsetcolor=RGB(255,0,0)(buf, 0, sizeof"  此时“=”两边不会有空格(buf));  GetPrivateProfileSectionNames(buf, nSize, strCfgPath);//等于GetPrivateProfileString(NULL, NULL, _T(""), buf, nSize, strCfgPath);

  //buf: "FontBOOLLayoutWritePrivateProfileString(Body LPCTSTR"

lpAppName, // section name

 LPCTSTRlpKeyName, // key name 

LPCTSTRlpString,  // string to add

 LPCTSTR

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

lpFileName // initialization file

);The WritePrivateProfileSection function replaces the keys and values forthe specified section in an initialization file.

BOOLWritePrivateProfileSection(  LPCTSTR

lpAppName, // section name  LPCTSTR

lpString,  // data  LPCTSTR

lpFileName

// file name); WritePrivateProfileString(_T(

"Layout" ), _T(

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

  WritePrivateProfileString(_T( "Layout"), _T(

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

  

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

//删除某Section,包括[Layout]和其下所有Keys=Value  WritePrivateProfileSection(_T("Layout"), NULL, strCfgPath);  

//删除某Section,包括[Layout]下所有Keys=Value,但不删除[Layout]  WritePrivateProfileSection(_T("Layout"), _T(""), strCfgPath);

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

std::vector;usingstd::map;//获取ini文件的所有Section名

LPCTSTRszIniFilePath)  

  TCHARbuf[2048] = { 0 };  longnSize =

sizeof(buf) /

自己封装的函数:

获取某一个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

sizeof (buf[0]);

   ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  

vector GetSectionsNames(TCHAR *p, *q;

{

  vector vRet;

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

LPCTSTRszSection,

LPCTSTRszIniFilePath)

    

TCHARbuf[2048] = { 0 };

  long

nSize = sizeof

(buf) / sizeof (buf[0]);

  

GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

map GetKeysValues(   TCHAR* p = buf;   

{

TCHARmap mapRet;

* 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;  

}  

returnmapRet;

}

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1329897.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存