regex練習之作,雖然讀ini是很古老的東西,但不可否認還真的蠻實用的。GetPrivateProfile嚴格的說是沒有讀array的機制,假設我的ini中有二個array key分別為:
[Para]
Para1 = 0.0952, 1.0, .0, .14, 1.0, 0.0, 1.0
Para2 = 2, 3, 2, 1, 1, 7, 1, 2, 0, 1
我設計GetPrivateProfileDoubleArray用來讀浮點數陣列(Para1),透過regex可以很快的把數值分割出來,再將分割的字串轉換回浮點數即可,用法如下:
1: double pPara1[10] = { 0 };
2: GetPrivateProfileDoubleArray("Para","Para1",pPara1,10,strIniPath);
GetPrivateProfileDoubleArray函式有一個缺點,ini中的數值格式最少要有一位小數點,如果是整數會被忽略。GetPrivateProfileDoubleArray程式碼:
1: DWORD GetPrivateProfileDoubleArray(LPCTSTR lpszSec,LPCTSTR lpszKey,double* pArray,int nSafeSize,LPCTSTR lpszFilePath)
2: {
3: TCHAR szData[_MAX_PATH] = { 0 };
4:
5: if(GetPrivateProfileString(lpszSec,lpszKey,"",szData,_MAX_PATH,lpszFilePath) == 0) return 0;
6:
7: const regex refloat("\\d*\\.\\d+");
8: const sregex_token_iterator end;
9:
10: string s = szData;
11: int i = 0;
12: for(sregex_token_iterator value(s.begin(), s.end(), refloat) ; value != end ; ++value)
13: {
14: if(i >= nSafeSize) break;
15:
16: string sv = *value;
17:
18: pArray[i++] = atof(sv.c_str());
19: }
20:
21: return i;
22: }
用GetPrivateProfileShortArray讀整數陣列(Para2)
1: short pPara2[10] = { 0 };
2: GetPrivateProfileShortArray("Para","Para2",pPara2,10,strIniPath);
GetPrivateProfileShortArray程式碼:
1: DWORD GetPrivateProfileShortArray(LPCTSTR lpszSec,LPCTSTR lpszKey,short* pArray,int nSafeSize,LPCTSTR lpszFilePath)
2: {
3: TCHAR szData[_MAX_PATH] = { 0 };
4:
5: if(GetPrivateProfileString(lpszSec,lpszKey,"",szData,_MAX_PATH,lpszFilePath) == 0) return 0;
6:
7: const regex refloat("\\d+");
8: const sregex_token_iterator end;
9:
10: string s = szData;
11: int i = 0;
12: for(sregex_token_iterator value(s.begin(), s.end(), refloat) ; value != end ; ++value)
13: {
14: if(i >= nSafeSize) break;
15:
16: string sv = *value;
17:
18: pArray[i++] = atoi(sv.c_str());
19: }
20:
21: return i;
22: }