尝试从C ++中的ini文件读取

T.S*_*erd -1 c++ winapi ini

因此,我决定承担一种新的爱好,因为我无力建造PC,到目前为止,我还是试图创建一个基于控制台的简单程序,该程序从ini文件中读取信息,但是似乎根本无法读取它,并且而是仅输出默认值。和随机整数。

char* ReadINI(const char* sSection, const char* sSub, const char* sDefaultValue)
{
    char* sResult = new char[255];
    memset(szResult, 0x00, 255);
    GetPrivateProfileString(  sSection, sSub, sDefaultValue, sResult, 255, ".\\config.ini");
    return sResult;
}

int s_width = (int)ReadINI("CONFIGURATION", "WIN_WIDTH", 0);
int s_height = (int)ReadINI("CONFIGURATION", "WIN_HEIGHT", 0);
const char* value = ReadINI("CONFIGURATION", "WIN_NAME", "null");
Run Code Online (Sandbox Code Playgroud)

这是我作为调试方式的输出,因此用户知道该应用程序已正确读取那里的设置。

std::cout << "Width: " << s_width << "\n"; // Displays random integer
std::cout << "Height: " << s_height << "\n"; // Displays random integer
std::cout << "Name: " << value << "\n "; // Displays null
Run Code Online (Sandbox Code Playgroud)

这是我的.ini文件

[CONFIGURATION]
WIN_NAME="Notepad"
WIN_WIDTH="800"
WIN_HEIGHT="600"
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 6

不要将相对路径传递给(Get|Write)PrivateProfile...函数,而需要传递绝对路径。PrivateProfile API将相对路径解释为相对于Windows安装文件夹,而不是相对于调用进程当前工作目录的相对路径,正如您所期望的那样。这是记录的行为

lpFileName

初始化文件的名称。如果此参数不包含文件的完整路径,则系统在Windows目录中搜索文件。

您实际上并不是从.ini文件中读取数据,因此可以返回指定的默认值。

您无法将char*指针类型转换为int以获得所需的数字值。您正在打印出char*指向的内存地址,而不是字符串表示的整数值。您需要解析的字符串,如使用Win32 StrToInt(),或C- sscanf()或C ++标准库std::atoi()std::stoi()std::istringstream。在这种情况下,更好的解决方案是改用GetPrivateProfileInt()API,让API为您进行解析。

您还会泄漏char*分配的字符串。您应该改用std::string标准的C ++库来为您处理内存管理。

话虽如此,请尝试类似以下的操作:

std::string configFile;

std::string ReadINI_String(const std::string &sSection, const std::string &sSub, const std::string &sDefaultValue)
{
    char sResult[256] = {};
    GetPrivateProfileString( sSection.c_str(), sSub.c_str(), sDefaultValue.c_str(), sResult, 255, configFile.c_str() );
    return sResult;
}

int ReadINI_Int(const std::string &sSection, const std::string &sSub, int iDefaultValue)
{
    return GetPrivateProfileInt( sSection.c_str(), sSub.c_str(), iDefaultValue, configFile.c_str() );
}

...

char path[MAX_PATH] = {};
GetModuleFileNameA(NULL, path, MAX_PATH);
PathRemoveFileSpecA(path);
PathCombineA(path, path, "config.ini");
configFile = path;

...

int i_width = ReadINI_Int("CONFIGURATION", "WIN_WIDTH", 0);
int i_height = ReadINI_Int("CONFIGURATION", "WIN_HEIGHT", 0);
std::string s_value = ReadINI_String("CONFIGURATION", "WIN_NAME", "null");

std::cout << "Width: " << i_width << "\n";
std::cout << "Height: " << i_height << "\n";
std::cout << "Name: " << s_value << "\n";
Run Code Online (Sandbox Code Playgroud)