INI 檔案的詳細說明,可參考Windows 官方網站之說明(連結

Windows本身提供了 標準的 API 可以針對INI 檔進行操作與處理,分別為GetPrivateProfileStringWritePrivateProfileString。

然後上述兩個函數中的檔案名稱需要使用目標 INI 檔的完整路徑(需使用絕對路徑,不可使用相對路徑)。

然而程式可能都操作固定的某個 INI 檔,但是每次存取都需要取得該檔案之路徑,故將其行為進行簡易的彙整與處理。

並將其撰寫成 較方便使用的 Class 以便日後進行使用:

 

InIHelper.hpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#pragma once

#include <windows.h>
#include <iostream>

#define INI_SESSION_NAME L"SESSION_NAME"
#define INI_KEY_PATH L"Path"

using std::string;
using std::wstring;


class InIHelper
{
private:
	string ini_filename;
	//string get_current_folder();

public:
	InIHelper(string filename);
	~InIHelper();

	wstring get(LPWSTR session, LPWSTR key, LPWSTR str_default);
	DWORD write(LPWSTR session, LPWSTR key, LPWSTR value);

};

為了讀取資料與寫入資料時,Session 與 Key 值能夠一致,故將會使用到的 Session 名稱與 Key 值,透過 Marco 進行定義。

 

InIHelper.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "InIHelper.h"

string get_current_folder(){
	wchar_t exeFullPath[MAX_PATH]; // Full path   
	std::string strPath = "";
	GetModuleFileName(NULL, exeFullPath, MAX_PATH);
	char CharString[MAX_PATH];
	size_t convertedChars = 0;
	wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath, _TRUNCATE);

	strPath = (std::string)CharString;    // Get full path of the file   
	int pos = strPath.find_last_of('\\', strPath.length());
	return strPath.substr(0, pos);  // Return the directory without the file name   
	//return strPath; // Return the directory include the file name   
}

InIHelper::InIHelper(string filename)
{
	this->ini_filename = get_current_folder() + "\\" + filename;
}


InIHelper::~InIHelper()
{

}

wstring InIHelper::get(LPWSTR session, LPWSTR key, LPWSTR str_default){
	std::wstring stemp = std::wstring(this->ini_filename.begin(), this->ini_filename.end());
	LPCWSTR sw = stemp.c_str();
	TCHAR temp[255];
	DWORD dwRet = GetPrivateProfileString(session, key, str_default, temp, sizeof(temp), sw);
	return wstring(temp);
}
DWORD InIHelper::write(LPWSTR session, LPWSTR key, LPWSTR value){
	std::wstring stemp = std::wstring(this->ini_filename.begin(), this->ini_filename.end());
	LPCWSTR sw = stemp.c_str();
	DWORD dwRet = WritePrivateProfileString(session, key, value, sw);

	return dwRet;
}

 

Source.cpp

1
2
InIHelper iniHelper("setup.ini");
std::wcout << iniHelper.get(INI_SESSION_NAME, INI_KEY_PATH, L"") << std::endl;

 

建立物件時,指定檔案名稱即可(此 Class 預設為與執行檔同層目錄夾)

並透過 get 與 write 進行資料的讀寫操作。

arrow
arrow
    文章標籤
    c++
    全站熱搜
    創作者介紹
    創作者 Lung-Yu,Tsai 的頭像
    Lung-Yu,Tsai

    Lung-Yu,Tsai 的部落格

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()