C++ Windowsで ini ファイルを読み込む
はじめに
Windows で、ini ファイルの読み込みと言えば、GetPrivateProfileString
です。
時間をかけずに、手っ取り早く設定ファイル対応を行うときに使えるかもしれない方法です。
注意
GetPrivateProfileString は、下記に引用した通り
16ビット互換 のために残されているAPIなので、非推奨
と考えた方がよさそうです。
MSDN より引用
注意 この関数は、16 ビット Windows ベースのアプリケーションとの互換性を保つ目的でのみ提供されています。Win32 ベースのアプリケーションでは、初期化情報をレジストリに格納してください。
実装
- config.ini
; 設定ファイル [System] WindowText = ウィンドウタイトル WindowWidth = 1280 WindowHeight = 720
- main.cpp
#include <Windows.h> // GetPrivateProfileString #include <iostream> // cout #include <array> // array #include <string> // string std::string GetConfigString(const std::string& filePath, const char* pSectionName, const char* pKeyName) { if (filePath.empty()) { return ""; } std::array<char, MAX_PATH> buf = {}; GetPrivateProfileStringA(pSectionName, pKeyName, "", &buf.front(), static_cast<DWORD>(buf.size()), filePath.c_str()); return &buf.front(); } int main() { std::string filePath = ".\\config.ini"; auto WindowText = GetConfigString(filePath, "System", "WindowText"); auto WindowWidth = GetConfigString(filePath, "System", "WindowWidth"); auto WindowHeight = GetConfigString(filePath, "System", "WindowHeight"); std::cout << WindowText << std::endl; std::cout << WindowWidth << std::endl; std::cout << WindowHeight << std::endl; system("pause"); return 0; }
あとがき
APIの引数的に、情報取得毎にファイルを読み込みに行く疑惑があるので、
もしかすると、ファイルサイズの影響を受けて、遅くなるかもしれません。
そもそも、互換目的で残されているだけっぽいので、代替機能を用意するなり、適宜対応した方が良さそう。