Como ler config-entradas de arquivo de um arquivo INI
Pergunta
Eu não pode usar as funções Get*Profile
porque eu estou usando uma versão mais antiga do SDK da plataforma Windows CE que não tem esses. Ele não tem que ser muito geral.
[section]
name = some string
Eu só preciso abrir o arquivo, verifique a existência de "seção", e o valor associado com "nome". Padrão C ++ é preferido.
Solução
O que eu vim com:
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
WCHAR _line[256];
file.getline(_line, ELEMENTS(_line));
std::wstringstream lineStm(_line);
std::wstring &line=lineStm.str();
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
for (size_t i=1; i<line.length(); i++)
{
if (line[i]!=L']')
header.push_back(line[i]);
else
break;
}
if (header==L"Section")
section=true;
else
section=false;
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
Outras dicas
Você deve ter um olhar para Boost.Program_options . Ele tem uma função parse_config_file que enche um mapa de variáveis. Apenas o que você precisa!
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow