1. 程式人生 > >【MFC】VC讀寫ini檔案

【MFC】VC讀寫ini檔案

可以用於載入時,讀取上一次的紀錄。

一:寫ini配置檔案:

    //獲取exe路徑
    CString  strPath;   
    GetModuleFileName(NULL,strPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);   
    strPath.ReleaseBuffer();   
    int nPos = strPath.ReverseFind('\\');   
    strPath=strPath.Left(nPos);   
    strPath += "\\test.ini";

    //向INI檔案中新增鍵值 
    WritePrivateProfileString ("HiddenFltCofig", "LogType", logType, strPath); 
    WritePrivateProfileString ("HiddenFltCofig", "LogPath", logPath, strPath); 
    WritePrivateProfileString ("HiddenFltCofig", "LogConfigFilePath", logAnalyseConfigFile, strPath); 
    WritePrivateProfileString ("HiddenFltCofig", "InventoryInfo", inventoryInfo, strPath); 
    WritePrivateProfileString ("HiddenFltCofig", "FailureCriteriaPath", failureCriteriaPath, strPath); 
    WritePrivateProfileString ("HiddenFltCofig", "LogExportPath", exportMiddleLogExcelPath, strPath); 

ini檔案中將呈現:

[HiddenFltCofig]
LogPath=D:\faultlog
LogConfigFilePath=D:config\CFT
InventoryInfo=D:\evdoc
FailureCriteriaPath=D:\21228.xlsx
LogExportPath=

:讀ini配置檔案

    CString logType;
    CString logPath;
    CString logAnalyseConfigFile;
    CString inventoryInfo;
    CString failureCriteriaPath;
    CString exportMiddleLogExcelPath;

    CString  strPath;   
    GetModuleFileName(NULL,strPath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);   
    strPath.ReleaseBuffer();   
    int nPos;   
    nPos=strPath.ReverseFind('\\');   
    strPath=strPath.Left(nPos);   
    strPath += "\\test.ini"; 

    GetPrivateProfileString("HiddenFltCofig", "LogType", 0,  logType.GetBuffer(MAX_PATH),MAX_PATH, strPath);
    GetPrivateProfileString("HiddenFltCofig", "LogPath", 0,  logPath.GetBuffer(MAX_PATH),MAX_PATH, strPath);
    GetPrivateProfileString("HiddenFltCofig", "LogConfigFilePath", 0,  logAnalyseConfigFile.GetBuffer(MAX_PATH),MAX_PATH, strPath); 
    GetPrivateProfileString("HiddenFltCofig", "InventoryInfo", 0,  inventoryInfo.GetBuffer(MAX_PATH),MAX_PATH, strPath); 
    GetPrivateProfileString("HiddenFltCofig", "FailureCriteriaPath", 0,  failureCriteriaPath.GetBuffer(MAX_PATH),MAX_PATH, strPath); 
    GetPrivateProfileString("HiddenFltCofig", "LogExportPath", 0,  exportMiddleLogExcelPath.GetBuffer(MAX_PATH),MAX_PATH, strPath); 

    //在這裡必須ReleaseBuffer(),否則無法再後面進行字串的連線
    logPath.ReleaseBuffer();
    logAnalyseConfigFile.ReleaseBuffer();
    inventoryInfo.ReleaseBuffer();
    failureCriteriaPath.ReleaseBuffer();
    exportMiddleLogExcelPath.ReleaseBuffer();
以上已經讀入內容,可以輸出到介面上:
    SetDlgItemText(IDC_EDIT_HIDDEN_LOG_PATH, logPath);
    SetDlgItemText(IDC_EDIT_HIDDEN_LOG_CONFIG_FILE, logAnalyseConfigFile);
    SetDlgItemText(IDC_EDIT_INVENTORY_INFO_FILE, inventoryInfo);
    SetDlgItemText(IDC_EDIT_FAILURE_CRITERIA_PATH, failureCriteriaPath);
    SetDlgItemText(IDC_EDIT_HIDDEN_EXPORT_PATH, exportMiddleLogExcelPath);