如何在 C++ 中读取与反斜杠分隔的键对应的值

How to read values corresponding to a key separated by backslash in c++

我在 ini 文件中有一个部分我想用 C++ 读取和解析

我试图在 GetPrivateProfileString 的帮助下读取它,但它读取到“$THIS$=somevalue”,\并且没有进一步读取。

file.ini

[Mysection]
UserDefinedVariables="$THIS$=somevalue",\
"$THAT$=somevalue1",\
"$DEVICE1$=somevalue2",\
"$DEVICE2$=somevalue3",\
"$DEVICE3$=somevalue4"

c++ 文件

wchar_t deviceName[200];
GetPrivateProfileString(L"Mysection", L"UserDefinedVariables", NULL, deviceName, sizeof(deviceName), file.ini);

这里我对对应于 $DEVICE1$ 的值特别感兴趣,即 somevalue2。 有什么方法可以利用 windows API 来阅读它吗?

是的。您可以使用此功能。但我怀疑这是你想要做的。

问题是你的输入文件有误。末尾的 \ 通常是行的连接符。所以,所有的文本都应该在一行中。然后应该解析结果。

下一行再次被视为具有值的键。

但密钥不是您所期望的$DEVICE1$,而是“$DEVICE1$。请参阅附加”。请阅读函数 docu.

如果您搜索该键,您将得到一个结果。但这里又附加了一个 ".

所以下面几行的格式不正确,原因是我之前解释过的。要了解此功能的工作原理(您首先不应该使用它),请参阅以下代码:

#include <Windows.h>
#include <iostream>

int main()
{
    wchar_t deviceName[400];

    GetPrivateProfileString(L"Mysection", L"UserDefinedVariables", NULL, deviceName, sizeof(deviceName), L"r:\file.ini");
    std::wcout << "searching for key UserDefinedVariables --> " << deviceName << '\n';


    // Get all keys
    std::wcout << "\n\nSearching for all keys in section:\n";
    DWORD size = GetPrivateProfileString(L"Mysection", NULL, NULL, deviceName, sizeof(deviceName), L"r:\file.ini");

    DWORD start = 0;
    wchar_t keys[10][100];
    DWORD keyIndex = 0;

    for (DWORD i = 0; i < size; ++i) {
        if (deviceName[i] == 0) {
#pragma warning(suppress : 4996)
            wcscpy(keys[keyIndex], deviceName + start);
            start = i + 1;
            std::wcout << keys[keyIndex] << '\n';
            ++keyIndex;
        }
    }

    // Getting all values for the keys
    std::wcout << "\n\nSearching for all keys with values in section:\n";

    for (DWORD i = 0; i < keyIndex; ++i) {
        GetPrivateProfileString(L"Mysection", keys[i], NULL, deviceName, sizeof(deviceName), L"r:\file.ini");
        std::wcout << keys[i] << " -->  " << deviceName << '\n';
    }
    return 0;
}

结果:

searching for key UserDefinedVariables --> "$THIS$=somevalue",\


Searching for all keys in section:
UserDefinedVariables
"$THAT$
"$DEVICE1$
"$DEVICE2$
"$DEVICE3$


Searching for all keys with values in section:
UserDefinedVariables -->  "$THIS$=somevalue",\
"$THAT$ -->  somevalue1",\
"$DEVICE1$ -->  somevalue2",\
"$DEVICE2$ -->  somevalue3",\
"$DEVICE3$ -->  somevalue4"

然后您可以随心所欲地提取您的值。

但正如我所说。最好更正ini文件。