Cómo leer las entradas del archivo de configuración de un archivo INI
Pregunta
No puedo usar las funciones Get * Profile
porque estoy usando una versión anterior del SDK de la plataforma Windows CE que no tiene esas. No tiene que ser demasiado general.
[section]
name = some string
Solo necesito abrir el archivo, verificar la existencia de la sección " " ;, y el valor asociado con " nombre " ;. Se prefiere C ++ estándar.
Solución
Lo que se me ocurrió:
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;
}
}
}
}
Otros consejos
Debería consultar Boost.Program_options . Tiene una función parse_config_file que llena un mapa de variables. Justo lo que necesitas!
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow