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

举报
风吹稻花香 发表于 2022/06/10 00:49:39 2022/06/10
【摘要】 目录 fstream读取txt windows读取节点  GxxPropertyUtils 读取key/value 在Windows的VC下 fstream读取txt aaaa.h void loadClassList(string m_classfile);vector<std::string&gt...

目录

fstream读取txt

windows读取节点

 GxxPropertyUtils 读取key/value

在Windows的VC下


fstream读取txt

aaaa.h


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

aaaa.cpp


  
  1. #include <fstream>
  2. void Detector::loadClassList(string m_classfile)
  3. {
  4. std::ifstream ifs(m_classfile);
  5. std::string line;
  6. while (getline(ifs, line))
  7. m_classNames.push_back(line);
  8. }

windows读取节点


  
  1. LPTSTR lpPath = new char[MAX_PATH];
  2. strcpy(lpPath, "D:\\IniFileName.ini");
  3. WritePrivateProfileString("LiMing", "Sex", "Man", lpPath);
  4. WritePrivateProfileString("LiMing", "Age", "20", lpPath);
  5. WritePrivateProfileString("Fangfang", "Sex", "Woman", lpPath);
  6. WritePrivateProfileString("Fangfang", "Age", "21", lpPath);
  7. delete [] lpPath;
  8. //INI文件如下:
  9. [LiMing]
  10. Sex=Man
  11. Age=20
  12. [Fangfang]
  13. Sex=Woman
  14. Age=21
  15. 读INI文件:
  16. LPTSTR lpPath = new char[MAX_PATH];
  17. LPTSTR LiMingSex = new char[6];
  18. int LiMingAge;
  19. LPTSTR FangfangSex = new char[6];
  20. int FangfangAge;
  21. strcpy(lpPath, "..\\IniFileName.ini");
  22. GetPrivateProfileString("LiMing", "Sex", "", LiMingSex, 6, lpPath);
  23. LiMingAge = GetPrivateProfileInt("LiMing", "Age", 0, lpPath);
  24. GetPrivateProfileString("Fangfang", "Sex", "", FangfangSex, 6, lpPath);
  25. FangfangAge = GetPrivateProfileInt("Fangfang", "Age", 0, lpPath);
  26. delete [] lpPath;

 GxxPropertyUtils 读取key/value

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

调用示例:

123.conf


  
  1. [LiMing]
  2. #server ip port
  3. server.ip=127.0.0.1
  4. server.port = 8080
  5. [test]
  6. name=asdf

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


  
  1. #include "GxxPropertyUtils.h"
  2. using namespace cv;
  3. int main(int argc, char* argv[]) {
  4. GxxPropertyUtils::ConfigFile* cf = GxxPropertyUtils::OpenConfigFile("d:\\123.conf");
  5. std::string servIp = GxxPropertyUtils::GetPropertyString(cf, "server.ip");
  6. cout << servIp << endl;
  7. servIp = GxxPropertyUtils::GetPropertyString(cf, "server.port");
  8. cout << servIp << endl;
  9. GxxPropertyUtils::Close(cf);
  10. }

GxxPropertyUtils.h


  
  1. #pragma once
  2. #include <string>
  3. namespace StringUtils {
  4. bool inline isBlank(char ch) {
  5. return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\0';
  6. }
  7. bool inline isBlank(wchar_t ch) {
  8. return ch == L' ' || ch == L'\t' || ch == L'\r' || ch == L'\n' || ch == '\0';
  9. }
  10. }
  11. namespace GxxPropertyUtils
  12. {
  13. struct ConfigFile;
  14. /**
  15. * 打开类似以下文件格式的配置文件
  16. * #server ip port
  17. * server.ip = 127.0.0.1
  18. * server.port = 8080
  19. */
  20. ConfigFile* OpenConfigFile(const char* filepath, bool bReadonly = true);
  21. /**
  22. * 保存配置
  23. */
  24. void Save(ConfigFile* cf);
  25. /**
  26. * 关闭配置, 如果配置有发生变化,则自动保存
  27. */
  28. void Close(ConfigFile* cf);
  29. std::string GetPropertyString(ConfigFile* cf, const char* key, const char* defaultV = "");
  30. bool GetPropertyBool(ConfigFile* cf, const char* key, bool defaultV = false);
  31. int GetPropertyInteger(ConfigFile* cf, const char* key, int defaultV = 0);
  32. void WriteProperty(ConfigFile* cf, const char* key, const char* v);
  33. void WriteProperty(ConfigFile* cf, const char* key, bool v);
  34. void WriteProperty(ConfigFile* cf, const char* key, int v);
  35. }

GxxPropertyUtils.cpp


  
  1. #include "GxxPropertyUtils.h"
  2. #include <fstream>
  3. #include <vector>
  4. #include <map>
  5. #include <string>
  6. using namespace std;
  7. namespace GxxPropertyUtils {
  8. struct ConfigFileLine {
  9. short lineType; // 0:注释, 1:配置, 2:无效行
  10. string strLine;
  11. string strKey;
  12. string strValue;
  13. };
  14. struct ConfigFile {
  15. string filepath;
  16. bool readonly;
  17. bool modified;
  18. vector<ConfigFileLine> lines;
  19. map<string, int> mapV;
  20. };
  21. ConfigFile* OpenConfigFile(const char* filepath, bool bReadonly)
  22. {
  23. char buf[1025];
  24. int nLen;
  25. ConfigFile* pcf = new ConfigFile;
  26. try {
  27. pcf->filepath = filepath;
  28. pcf->readonly = bReadonly;
  29. pcf->modified = false;
  30. ifstream fd(filepath, ios_base::in | ios_base::_Nocreate);
  31. if (!fd.is_open())
  32. return pcf;
  33. while (!fd.eof()) {
  34. fd.getline(buf, 1024);
  35. nLen = strlen(buf);
  36. const char* pL = nullptr;
  37. const char* pLEnd = nullptr;
  38. const char* pR = nullptr;
  39. const char* p = buf;
  40. ConfigFileLine li;
  41. bool isComment = false;
  42. while (*p) {
  43. if (StringUtils::isBlank(*p)) {
  44. p++; continue;
  45. }
  46. if (*p == '#') {
  47. isComment = true; break;
  48. }
  49. pL = p;
  50. break;
  51. }
  52. if (isComment) {
  53. li.lineType = 0;
  54. li.strLine = buf;
  55. pcf->lines.push_back(li);
  56. continue;
  57. }
  58. if (pL == nullptr) {
  59. // 无效
  60. li.lineType = 2;
  61. li.strLine = buf;
  62. pcf->lines.push_back(li);
  63. continue;
  64. }
  65. while (*++p) {
  66. if (StringUtils::isBlank(*p) || *p == '=') {
  67. pLEnd = p;
  68. break;
  69. }
  70. }
  71. if (pLEnd == nullptr) {
  72. // 无效
  73. li.lineType = 2;
  74. li.strLine = buf;
  75. pcf->lines.push_back(li);
  76. continue;
  77. }
  78. while (*p) {
  79. if (*p == '=' || StringUtils::isBlank(*p)) {
  80. p++;
  81. continue;
  82. }
  83. pR = p;
  84. break;
  85. }
  86. if (pR == nullptr) {
  87. // 无效
  88. li.lineType = 2;
  89. li.strLine = buf;
  90. pcf->lines.push_back(li);
  91. continue;
  92. }
  93. p = buf + nLen;
  94. while (p != pR) {
  95. if (!StringUtils::isBlank(*p))
  96. break;
  97. --p;
  98. }
  99. li.lineType = 1;
  100. li.strLine = buf;
  101. li.strKey = string(pL, pLEnd - pL);
  102. li.strValue = string(pR, p - pR + 1);
  103. pcf->lines.push_back(li);
  104. pcf->mapV[li.strKey] = (int)pcf->lines.size() - 1;
  105. }
  106. fd.close();
  107. }
  108. catch (...) {
  109. delete pcf;
  110. return nullptr;
  111. }
  112. return pcf;
  113. }
  114. void Save(ConfigFile* cf)
  115. {
  116. if (!cf->readonly && cf->modified) {
  117. try {
  118. ofstream o(cf->filepath, ios_base::out);
  119. for (auto it = cf->lines.begin(); it != cf->lines.end(); ++it) {
  120. o << it->strLine << endl;
  121. }
  122. o.close();
  123. }
  124. catch (...) {
  125. }
  126. }
  127. }
  128. void Close(ConfigFile* cf)
  129. {
  130. Save(cf);
  131. delete cf;
  132. }
  133. std::string GetPropertyString(ConfigFile* cf, const char* key, const char* defaultV/*=""*/)
  134. {
  135. auto it = cf->mapV.find(string(key));
  136. if (it == cf->mapV.end())
  137. return string(defaultV);
  138. return cf->lines[it->second].strValue;
  139. }
  140. bool GetPropertyBool(ConfigFile* cf, const char* key, bool defaultV /*= false*/)
  141. {
  142. auto it = cf->mapV.find(string(key));
  143. if (it == cf->mapV.end())
  144. return defaultV;
  145. const string& v = cf->lines[it->second].strValue;
  146. if (v == "true")
  147. return true;
  148. return false;
  149. }
  150. int GetPropertyInteger(ConfigFile* cf, const char* key, int defaultV /*= 0*/)
  151. {
  152. auto it = cf->mapV.find(string(key));
  153. if (it == cf->mapV.end())
  154. return defaultV;
  155. const string& v = cf->lines[it->second].strValue;
  156. return atoi(v.c_str());
  157. }
  158. void WriteProperty(ConfigFile* cf, const char* key, const char* v)
  159. {
  160. string sKey(key);
  161. auto it = cf->mapV.find(sKey);
  162. if (it == cf->mapV.end()) {
  163. ConfigFileLine li;
  164. li.lineType = 1;
  165. li.strKey = key;
  166. li.strValue = (v == nullptr ? "" : v);
  167. li.strLine.append(li.strKey);
  168. li.strLine.append(" = ");
  169. li.strLine.append(li.strValue);
  170. cf->lines.push_back(li);
  171. cf->mapV[sKey] = cf->lines.size() - 1;
  172. }
  173. else {
  174. auto& li = cf->lines[it->second];
  175. li.strLine = li.strKey;
  176. li.strValue = (v == nullptr ? "" : v);
  177. li.strLine.append(" = ");
  178. li.strLine.append(li.strValue);
  179. }
  180. cf->modified = true;
  181. }
  182. void WriteProperty(ConfigFile* cf, const char* key, bool v)
  183. {
  184. WriteProperty(cf, key, v ? "true" : "false");
  185. }
  186. void WriteProperty(ConfigFile* cf, const char* key, int v)
  187. {
  188. char buf[12] = { 0 };
  189. _itoa_s(v, buf, 10);
  190. WriteProperty(cf, key, buf);
  191. }
  192. }

在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\0size\0color\0\0"

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

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

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

  //buf: "Font\0Layout\0Body\0\0"

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

  GetPrivateProfileSection(lpszSection, buf, nSize, strCfgPath);

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

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

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

  //buf: "Font\0Layout\0Body\0\0"

写ini文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

BOOL WritePrivateProfileString(

 LPCTSTR lpAppName, // section name

 LPCTSTR lpKeyName, // key name

 LPCTSTR lpString,  // string to add

 LPCTSTR lpFileName // initialization file

);

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

BOOL WritePrivateProfileSection(

 LPCTSTR lpAppName, // section name

 LPCTSTR lpString,  // data

 LPCTSTR lpFileName // file name

);

WritePrivateProfileString:

Remarks

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

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

WritePrivateProfileSection:

Remarks

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

key=string

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

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

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

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

例子:

1

2

3

4

5

6

7

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

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

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

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

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

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

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

自己封装的函数:

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

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

获取ini文件的所有Section名

vector<CString> 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 <vector>

#include <map>

using std::vector;

using std::map;

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

vector<CString> GetSectionsNames(LPCTSTR szIniFilePath)

{

  vector<CString> vRet;

  TCHAR buf[2048] = { 0 };

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

  ::GetPrivateProfileSectionNames(buf, nSize, szIniFilePath);

  TCHAR *p, *q;

  p = q = buf;

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

  {

    while (*q)

    {

      ++q;

    }

    CString str(p, q - p);

    vRet.push_back(str);

    p = q + 1;

    q = q + 1;

  }

  return vRet;

}

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

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

{

  map<CString,CString> mapRet;

  TCHAR buf[2048] = { 0 };

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

  GetPrivateProfileSection(szSection, buf, nSize, szIniFilePath);

  TCHAR* p = buf;

  TCHAR* q = buf;

  while (*p)

  {

    CString strKey, strValue;

    while(*q)

    {

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

      {

        strKey = CString(p, q - p);

        p = q + 1;

      }

      ++q;

    }

    strValue = CString(p, q - p);

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

    p = q + 1;

    q = q + 1;

  }

  return mapRet;

}

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

文章来源: blog.csdn.net,作者:AI视觉网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/125196031

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。