寫INI配置檔案
阿新 • • 發佈:2018-12-05
配置檔案經常採用ini檔案,window有相關API。
WritePrivateProfileString用於寫檔案
BOOL WritePrivateProfileString(
LPCTSTR lpAppName, // 欄位名,如果欄位名不存在,會被建立,可以建立多個欄位名
LPCTSTR lpKeyName, // 鍵名,屬於lpAppName,不存在會被建立;一個欄位名可以有多個鍵名
LPCTSTR lpString, // 鍵值,也就是資料
LPCTSTR lpFileName // INI檔案的路徑,如果不存在會被建立
);
示例程式碼(win7_64 +VS2012)
char cExecPath[MAX_PATH]; char* pszPathofFile; char pszFileName[MAX_PATH]; /* * Get the path of the program executable since this is where the ini * files are stored */ //獲得當前可執行程式絕對路徑 if(GetModuleFileName( 0, cExecPath, sizeof(cExecPath))) { pszPathofFile = strrchr(cExecPath, '\\'); /* remove the current EXE name from the path */ if(pszPathofFile) { *(pszPathofFile + 1) = '\0'; } } //拼接ini檔案路徑 sprintf_s( pszFileName, "%sCurrentProcessSetting.ini", cExecPath ); //key值 char keyValue[256]; sprintf_s( keyValue, "%d", 4 ); //欄位名 char* sectionValue = "Communication"; WritePrivateProfileString(sectionValue , "COM Port", keyValue, pszFileName);