VC++學習筆記---配置檔案(一) ini檔案和proprities
阿新 • • 發佈:2019-02-13
一、配置檔案
配置檔案 主要是描述系統的某些需要根據實際情況而設定變數的檔案入口。
作用:提高系統在各個環境的應用。例如:區域網軟體,可以根據實際的情況,修改軟體的IP地址,便於伺服器的靈活修改。
二、 VC++ 讀寫配置檔案
win32中,一般將副檔名命名為ini
2.1 配置檔案格式
格式:
[selection]
key=string
其中selection指定節名,key指定鍵值,string指定鍵值對應的鍵值。
2.2 寫入指定的字串
win32中使用writePrivateProfileString()函式可以想ini檔案中大的指定鍵值寫入字串資料。
BOOL WritePrivateProfileString(
LPCTSTR lpAppNAme, //指定要寫入的字串所在的節的名稱
LPCTSTR lpKeyName, //字串對應的鍵值
LPCTSTR lpString, //要寫入的字串
LPCTSTR lpFileName // 指定要寫入的字串的INI檔名
);
返回值 bool,如果是ture 表示寫入成功,否則寫入失敗
WritePrivateProfileString(
"DataBase",
"User",
"sa",
"param.ini"
);
生成的結果如下:在param.ini檔案中
[DataBase]
User=sa
2.3 獲取指定的值
讀取int型別的引數
GetPrivateProfileInt(
LPCTSTR lpAppName,//指定要寫入的字串所在的節的名稱
LPCTSTR lpKeyName,//字串對應的鍵值
INT nDefault, //如果不存在的預設值
LPCTSTR lpFileName// 指定要讀取的INI檔名
);
讀取字串型別的引數
GetPrivateProfileString(
LPCWSTR lpAppName,//指定要寫入的字串所在的節的名稱
LPCWSTR lpKeyName,//字串對應的鍵值
LPCWSTR lpDefault,//如果不存在的預設值
LPWSTR lpReturnedString, 獲取字串的緩衝區的指標
DWORD nSize, //指定結果緩衝區的大小
LPCWSTR lpFileName//指定ini檔名
);
2.4 寫入結構
WritePrivateProfileStruct(
LPCWSTR lpszSection, //指定要寫入的字串所在的節的名稱
LPCWSTR lpszKey,//字串對應的鍵值
LPVOID lpStruct,//寫入資料的指標
UINT uSizeStruct, //資料結構的大小
LPCWSTR szFile //ini檔名
);
2.5 讀取結構
GetPrivateProfileStruct(
LPCWSTR lpszSection, //指定要字串所在的節的名稱
LPCWSTR lpszKey,//字串對應的鍵值
LPVOID lpStruct,//讀取資料的指標
UINT uSizeStruct, //緩衝區大小
LPCWSTR szFile //ini檔名
);
2.6 向指定節寫入資料
WritePrivateProfileSection(
LPCWSTR lpszSection, //指定要字串所在的節的名稱
LPCWSTR lpszKey,//字串對應的鍵值
LPCWSTR szFile //ini檔名
);
WritePrivateProfileSection(
"student"
"username=sa\r\npassword=123",
"a.ini" //ini檔名
);
三、Java 讀寫配置檔案
3.1 讀取配置檔案
Properties properties = new Properties();
// 載入配置檔案
properties.load(new FileInputStream(new File("FTPDownload.ini")));
//讀取對應的變數
properties.getProperty("ip");
//讀取對應的變數,設定預設值
properties.getProperty("ip","127.0.0.1");
3.2 寫入配置檔案
Properties properties = new Properties();
//讀取對應的變數,設定預設值
properties.setProperty("ip","127.0.0.1");
properties.store(new FileOutputStream(new File("FTPDownload.ini")),"aaaa");