C++ 从具有重复项的INI文件中读取
我有以下INI文件:C++ 从具有重复项的INI文件中读取,c++,visual-c++,C++,Visual C++,我有以下INI文件: [Connection] Protocol=HTPP [Connection] Protocol=HTTPS 有什么方法可以在两个不同的变量中保存两个协议吗?我试着写: int a = GetPrivateProfileString(_T("Connection"), _T("Protocol"), _T(""), protocolChar, 32, path); int ab = GetPrivateProfileStr
[Connection]
Protocol=HTPP
[Connection]
Protocol=HTTPS
有什么方法可以在两个不同的变量中保存两个协议吗?我试着写:
int a = GetPrivateProfileString(_T("Connection"), _T("Protocol"), _T(""), protocolChar, 32, path);
int ab = GetPrivateProfileString(_T("Connection"), _T("Protocol"), _T(""), protocolChar2, 32, path);
结果是ProtocolChar,protocolChar2,虽然两者都接收“HTTP”。如何以不同的方式保留所有协议的变量?否,
GetPrivateProfileString
不支持具有相同名称的多个节,并且将始终使用它遇到的第一个节。有两种直接的方法可以使用。第一种方法是在每个节名称的末尾添加一个数字
[Connection0]
Protocol=HTPP
[Connection1]
Protocol=HTTPS
[Connection2]
Protocol=FTP
[Connection3]
Protocol=Telnet
使用这种方法,您可以迭代各种连接
部分,直到尝试加载一个不存在的部分
#include <windows.h>
#include <iostream>
#include <sstream>
int main()
{
for (DWORD i = 0, size = 1; size != 0; ++i)
{
std::ostringstream name;
name << "Connection" << i;
std::string protocol(100, 0);
size = GetPrivateProfileStringA(
name.str().c_str(),
"Protocol",
NULL,
&protocol[0],
protocol.size(),
"./test1.ini");
if (size != 0)
{
protocol.resize(size);
std::cout
<< name.str().c_str()
<< ":protocol=" << protocol << "\n";
}
}
}
使用这种方法,您可以迭代连接的条目
,然后加载每个单独的部分
#include <windows.h>
#include <iostream>
#include <sstream>
int main()
{
for (DWORD i = 0, size = 1; size != 0; ++i)
{
std::ostringstream name;
name << "Connection" << i;
std::string section(100, 0);
size = GetPrivateProfileStringA(
"Connections",
name.str().c_str(),
NULL,
§ion[0],
section.size(),
"./test1.ini");
if (size != 0)
{
section.resize(size);
std::string protocol(100, 0);
size = GetPrivateProfileStringA(
section.c_str(),
"Protocol",
NULL,
&protocol[0],
protocol.size(),
"./test1.ini");
if (size != 0)
{
protocol.resize(size);
std::cout
<< name.str().c_str()
<< ":"
<< section
<< ":protocol=" << protocol << "\n";
}
}
}
}
#包括
#包括
#包括
int main()
{
对于(DWORD i=0,size=1;size!=0;++i)
{
std::ostringstream名称;
我敢肯定,不要用GetPrivateProfileString
等命名。如果出于某种原因无法避免这种重复,您必须编写自己的INI文件解析器。这种情况的唯一解决方案是构建自己的INI文件解析器?这是我能想到的唯一解决方案。如果我知道另一个,我会提到它,不是吗?我不会没有严格的标准,但许多实现不会接受重复的节名,更不用说这种重复了。
#include <windows.h>
#include <iostream>
#include <sstream>
int main()
{
for (DWORD i = 0, size = 1; size != 0; ++i)
{
std::ostringstream name;
name << "Connection" << i;
std::string section(100, 0);
size = GetPrivateProfileStringA(
"Connections",
name.str().c_str(),
NULL,
§ion[0],
section.size(),
"./test1.ini");
if (size != 0)
{
section.resize(size);
std::string protocol(100, 0);
size = GetPrivateProfileStringA(
section.c_str(),
"Protocol",
NULL,
&protocol[0],
protocol.size(),
"./test1.ini");
if (size != 0)
{
protocol.resize(size);
std::cout
<< name.str().c_str()
<< ":"
<< section
<< ":protocol=" << protocol << "\n";
}
}
}
}