Сообщение было отмечено mastercard как решение
Решение
См. статью по .ini (Класс сделан для MFC, думаю, переделать Cstring На string не составит труда):
codeguru.com
Вот перевод:
Скачав и добавив в проект файлы CIniEx.h и CIniEx.cpp (ссылка ниже), можно открывать/создавать произвольное количество ini-файлов, сохранять и читать значения, получать список секций ini-файла и список ключей внутри любой секции, удалять ключ, секцию или содержимое ini-файла целиком -- всё это умеет класс CIniEx. Подробнее по каждому пункту:
1) открыть ini-файл можно тремя способами:
| C++ | 1
2
3
4
| CIniEx ini1, ini2, ini3;
ini1.Open("my_settings1.ini");
ini2.OpenAtExeDirectory("some2.ini");
ini3.OpenAtWindowsDirectory("another3.ini"); |
|
У каждого варианта функции Open есть несколько необязательных параметров-настроек, названия которых говорят сами за себя:
| C++ | 1
2
3
4
5
| BOOL CIniEx::Open(LPCSTR pFileName,
BOOL writeWhenChange /*=TRUE*/,
BOOL createIfNotExist /*=TRUE*/,
BOOL noCaseSensitive /*=TRUE*/,
BOOL makeBackup /*=FALSE*/) |
|
Закрывается файл автоматически, в деструкторе класса CIniEx
2) добавление или изменение значения ключа в ini-файле:
| C++ | 1
2
| ini1.SetValue("Section AAA", "Key Name", "Key Value");
ini1.SetValue("Секция БББ", "Имя Ключа", "Значение Ключа"); |
|
Если секция или ключ не существовали, то они будут созданы автоматически. Для записи в файл числовых значений, нужно перевести их в строковый формат (например, используя функции IntToStr, FloatToStr из нашего FAQ по С++). Можно также помещать ключи в ini-файл без указания секции -- такие ключи будут добавляться в так называемую "глобальную" (безымянную) секцию:
| C++ | 1
| ini1.SetValue("Global Key Name", "1234"); |
|
3) как получить список секций и ключей в секциях:
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| // перечислим все секции и ключи в файле "1.ini":
CIniEx file;
file.OpenAtExeDirectory("1.ini");
CStringArray sections; // динамический массив MFC для списка секций
file.GetSections(sections);
for(int i=0; i<sections.GetSize(); i++)
{
CString section = sections[i];
CStringArray keys; // динамический массив для списка ключей в секции
file.GetKeysInSection(section, keys);
for(int j=0; j<keys.GetSize(); j++)
{
CString key = keys[j]; // key равен имени ключа в секции section
}
} |
|
4) как получить значение по имени ключа:
| C++ | 1
| CString s = ini1.GetValue("Section AAA", "Key Name"); |
|
можно также читать значения ключей, расположенных в "глобальной" секции:
| C++ | 1
| CString s = ini1.GetValue("Global Key Name"); |
|
| C++ | 1
2
3
4
5
6
7
8
| // удаление ключа из секции
ini1.RemoveKey("Section AAA", "Key Name");
// удаление ключа из "глобальной" секции
ini1.RemoveKey("Global Key Name");
// удаление секции целиком
ini1.RemoveSection("Section AAA");
// очистка ini-файла
ini1.ResetContent(); |
|
Ещё одна возможность (полезная или нет, решайте сами) - это возможность автоматического создания backup-файла при сохранении ini-файла. За это отвечает соответствующий необязательный параметр функции Open; имя backup-файла можно настроить с помощью специальной функции SetBackupFileName(CString fileName).
|
Вот описываемый там класс:
| C++ | 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
| // IniEx.h: interface for the CIniEx class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_INIEX_H__36888C4C_12D3_4F65_A78B_2F3C3576B5B8__INCLUDED_)
#define AFX_INIEX_H__36888C4C_12D3_4F65_A78B_2F3C3576B5B8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_SECTION_COUNT 256
class CIniEx
{
private:
//Functions
int LookupKey (int nSectionIndex,CString *Key);
int LookupSection (CString *Section);
int CompareStrings (CString *str1,CString *str2);
void GrowIfNecessary (void);
void FindBackupFile (void);
private:
//Variables
CMapStringToString *m_tmpLines;
CString m_ErrStr;
CStringArray **m_Keys;
CStringArray **m_Values;
CStringArray m_Sections;
int m_SectionNo;
int m_GrowSize;
BOOL m_NoCaseSensitive;
BOOL m_writeWhenChange;
CString m_BackupFileName;
CString m_FileName;
BOOL m_makeBackup;
BOOL m_Changed;
public:
void GetKeysInSection(CString section,CStringArray &keys);
void GetSections(CStringArray §ions);
CIniEx(int GrowSize=4);
virtual ~CIniEx();
BOOL Open(LPCSTR pFileName,
BOOL writeWhenChange=TRUE,
BOOL createIfNotExist=TRUE,
BOOL noCaseSensitive=TRUE,
BOOL makeBackup=FALSE);
BOOL OpenAtExeDirectory(LPCSTR pFileName,
BOOL writeWhenChange=TRUE,
BOOL createIfNotExist=TRUE,
BOOL noCaseSensitive=TRUE,
BOOL makeBackup=FALSE);
void ResetContent();
CString WriteFile(BOOL makeBackup=FALSE);
CString GetValue(CString Section,CString Key,CString DefaultValue="");
CString GetValue(CString Key);
void SetValue(CString Key,CString Value);
void SetValue(CString Section,CString Key,CString Value);
BOOL RemoveKey(CString Key);
BOOL RemoveKey(CString Section,CString Key);
BOOL RemoveSection(CString Section);
BOOL GetWriteWhenChange();
void SetWriteWhenChange(BOOL WriteWhenChange);
void SetBackupFileName(CString &backupFile);
};
#endif // !defined(AFX_INIEX_H__36888C4C_12D3_4F65_A78B_2F3C3576B5B8__INCLUDED_) |
|
| C++ | 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
| // IniEx.cpp: implementation of the CIniEx class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "IniEx.h"
#include "malloc.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//GrowSize for Dynmiz Section Allocation
CIniEx::CIniEx(int GrowSize/*=4*/)
{
m_GrowSize=GrowSize;
m_SectionNo=0;
m_writeWhenChange=FALSE;
m_makeBackup=FALSE;
m_NoCaseSensitive=TRUE;
m_Changed=FALSE;
m_Keys=NULL;
m_Values=NULL;
}
CIniEx::~CIniEx()
{
if (m_writeWhenChange)
WriteFile(m_makeBackup);
ResetContent();
}
BOOL CIniEx::OpenAtExeDirectory(LPCSTR pFileName,
BOOL writeWhenChange,/*=TRUE*/
BOOL createIfNotExist/*=TRUE*/,
BOOL noCaseSensitive /*=TRUE*/,
BOOL makeBackup /*=FALSE*/)
{
CString filePath;
//if it's a dll argv will be NULL and it may cause memory leak
#ifndef _USRDLL
CString tmpFilePath;
int nPlace=0;
tmpFilePath=__argv[0];
nPlace=tmpFilePath.ReverseFind('\\');
if (nPlace!=-1)
{
filePath=tmpFilePath.Left(nPlace);
}
else
{
char curDir[MAX_PATH];
GetCurrentDirectory(MAX_PATH,curDir);
filePath=curDir;
}
#else
//it must be safe for dll's
char curDir[MAX_PATH];
GetCurrentDirectory(MAX_PATH,curDir);
filePath=curDir;
#endif
filePath+="\\";
filePath+=pFileName;
return Open(filePath,writeWhenChange,createIfNotExist,noCaseSensitive,makeBackup);
}
BOOL CIniEx::Open(LPCSTR pFileName,
BOOL writeWhenChange,/*=TRUE*/
BOOL createIfNotExist/*=TRUE*/,
BOOL noCaseSensitive /*=TRUE*/,
BOOL makeBackup /*=FALSE*/)
{
CFileException e;
BOOL bRet;
CString Line;
CString sectionStr;
int nPlace;
UINT mode=CFile::modeReadWrite;
//if it's second ini file for this instance
//we have to save it and delete member variables contents
if (!m_FileName.IsEmpty())
{
WriteFile();
ResetContent();
}
m_NoCaseSensitive=noCaseSensitive;
m_writeWhenChange=writeWhenChange;
m_makeBackup=makeBackup;
CString tmpKey;
CString tmpValue;
if (createIfNotExist)
mode= mode | CFile::modeCreate | CFile::modeNoTruncate;
try
{
CStdioFile file;
bRet=file.Open( pFileName, mode, &e );
if( !bRet )
{
return FALSE;
}
m_FileName=pFileName;
//Grow the arrays as GrowSize(which given constructor)
m_Keys=(CStringArray **)malloc( m_GrowSize * sizeof(CStringArray *) );
m_Values=(CStringArray **)malloc( m_GrowSize * sizeof(CStringArray *) );
for (int i=0;i<m_GrowSize;i++)
{
m_Keys[m_SectionNo+i]=NULL;
m_Values[m_SectionNo+i]=NULL;
}
//1.th section for sectionless ini files
m_Keys[m_SectionNo]=new CStringArray;
m_Values[m_SectionNo]=new CStringArray;
file.SeekToBegin();
while (TRUE)
{
//Read one line from given ini file
bRet=file.ReadString(Line);
if (!bRet) break;
//if line's first character = '['
//and last character = ']' it's section
if (Line.Left(1)=="[" && Line.Right(1)=="]")
{
m_SectionNo++;
GrowIfNecessary();
m_Keys[m_SectionNo]=new CStringArray;
m_Values[m_SectionNo]=new CStringArray;
sectionStr=Line.Mid(1,Line.GetLength()-2);
continue;
}
nPlace=Line.Find("=");
if (nPlace==-1)
{
tmpKey=Line;
tmpValue="";
}
else
{
tmpKey=Line.Left(nPlace);
tmpValue=Line.Mid(nPlace+1);
}
m_Keys[m_SectionNo]->Add(tmpKey);
m_Values[m_SectionNo]->Add(tmpValue);
m_Sections.SetAtGrow(m_SectionNo,sectionStr);
}
file.Close();
}
catch (CFileException *e)
{
m_ErrStr=e->m_cause;
}
return TRUE;
}
CString CIniEx::GetValue(CString Key)
{
return GetValue("",Key);
}
//if Section Name="" -> looking up key for witout section
CString CIniEx::GetValue(CString Section,CString Key,CString DefaultValue/*=""*/)
{
int nIndex=LookupSection(&Section);
if (nIndex==-1) return DefaultValue;
int nRet;
CString retStr;
for (int i=m_Keys[nIndex]->GetUpperBound();i>=0;i--)
{
nRet=CompareStrings(&m_Keys[nIndex]->GetAt(i),&Key);
if (nRet==0)
{
retStr=m_Values[nIndex]->GetAt(i);
int nPlace=retStr.ReverseFind(';');
if (nPlace!=-1) retStr.Delete(nPlace,retStr.GetLength()-nPlace);
return retStr;
}
}
return DefaultValue;
}
//returns index of key for given section
//if no result returns -1
int CIniEx::LookupKey(int nSectionIndex,CString *Key)
{
ASSERT(nSectionIndex<=m_SectionNo);
int nRet;
for (int i=m_Keys[nSectionIndex]->GetUpperBound();i>=0;i--)
{
nRet=CompareStrings(&m_Keys[nSectionIndex]->GetAt(i),Key);
if (nRet==0) return i;
}
return -1;
}
//return given sections index in array
int CIniEx::LookupSection(CString *Section)
{
int nRet;
for (int i=0;i<m_Sections.GetSize();i++)
{
nRet=CompareStrings(&m_Sections.GetAt(i),Section);
if (nRet==0) return i;
}
return -1;
}
//Sets for Key=Value for without section
void CIniEx::SetValue(CString Key,CString Value)
{
SetValue("",Key,Value);
}
//writes Key=value given section
void CIniEx::SetValue(CString Section,CString Key,CString Value)
{
//file opened?
ASSERT(!m_FileName.IsEmpty());
//if given key already existing, overwrite it
int nIndex=LookupSection(&Section);
int nKeyIndex;
if (nIndex==-1)
{
//if key not exist grow arrays (if necessary)
m_Changed=TRUE;
m_SectionNo++;
GrowIfNecessary();
m_Keys[m_SectionNo]=new CStringArray;
m_Values[m_SectionNo]=new CStringArray;
nIndex=m_SectionNo;
m_Sections.SetAtGrow(m_SectionNo,Section);
}
//looking up keys for section
nKeyIndex=LookupKey(nIndex,&Key);
//if key exist -> overwrite it
//if not add to end of array
if (nKeyIndex!=-1) //Bulundu ise;
{
//Var olan value'nun ьzerine yazэlэyor Fakat aynэsэ mэ diye kontrol ediliyor
//Aynэsэ deрil ise m_Chanced=TRUE yapэlmalэ ki Write iюlemi yapэlsэn.
if (CompareStrings(&m_Values[nIndex]->GetAt(nKeyIndex),&Value)!=0)
m_Changed=TRUE;
m_Values[nIndex]->SetAt(nKeyIndex,Value);
}
else //if not exist
{
m_Changed=TRUE;
m_Keys[nIndex]->Add(Key);
m_Values[nIndex]->Add(Value);
}
}
//returns backup file name
//if you didn't want backup (when openning file) it returns ""
CString CIniEx::WriteFile(BOOL makeBackup/*=FALSE*/)
{
if (!m_Changed) return "";
CString tmpFileName=m_FileName;
if (makeBackup)
{
if (m_BackupFileName.IsEmpty())
{
FindBackupFile();
}
//32768. Log dosyasэnda tekrar 1.nin ьzerine yazacak(FALSE ile)
BOOL ret=CopyFile(m_FileName,m_BackupFileName,FALSE);
}
CStdioFile file;
if (!file.Open(m_FileName,CFile::modeCreate | CFile::modeWrite))
{
#ifdef _DEBUG
afxDump << "ERROR!!!!: The file could not open for writing\n";
#endif
return "";
}
CString tmpLine;
for (int i=0;i<m_Sections.GetSize();i++)
{
if (!m_Sections.GetAt(i).IsEmpty())
{
tmpLine.Format("[%s]\n",m_Sections.GetAt(i));
file.WriteString(tmpLine);
}
if (!m_Keys[i]) continue;
for (int j=0;j<=m_Keys[i]->GetUpperBound();j++)
{
//if key is empts we don't write "="
tmpLine.Format("%s%s%s\n",m_Keys[i]->GetAt(j),
m_Keys[i]->GetAt(j).IsEmpty()?"":"=",
m_Values[i]->GetAt(j));
file.WriteString(tmpLine);
}
}
file.Close();
return m_BackupFileName;
}
BOOL CIniEx::GetWriteWhenChange(void)
{
return m_writeWhenChange;
}
void CIniEx::SetWriteWhenChange(BOOL WriteWhenChange)
{
m_writeWhenChange=WriteWhenChange;
}
void CIniEx::SetBackupFileName(CString &backupFile)
{
m_BackupFileName=backupFile;
}
void CIniEx::FindBackupFile(void)
{
WIN32_FIND_DATA ffData;
BOOL bContinue=TRUE;
CString filePath(m_FileName);
CString ext;
int nPlace=filePath.ReverseFind('.');
filePath.Delete(nPlace,filePath.GetLength()-nPlace);
filePath+="*.*";
int extNo=0;
char *p;
HANDLE handle=FindFirstFile(filePath,&ffData);
while (bContinue)
{
bContinue=FindNextFile(handle,&ffData);
p=ffData.cFileName;
p+=strlen(ffData.cFileName)-3;
if (atoi(p)>extNo) extNo=atoi(p);
}
m_BackupFileName.Format("%s.%.3d",m_FileName,extNo+1);
}
void CIniEx::ResetContent()
{
if (!m_Keys) return;
int alloctedObjectCount=_msize(m_Keys)/4;
if ( m_Keys)
{
for (int i=0;i<alloctedObjectCount;i++)
{
if (m_Keys[i])
delete m_Keys[i];
if (m_Values[i])
delete m_Values[i];
}
delete [] m_Keys;
delete [] m_Values;
}
m_Keys=NULL;
m_Values=NULL;
m_Sections.RemoveAll();
m_SectionNo=0;
m_FileName="";
m_Changed=FALSE;
}
//Removes key and it's value from given section
BOOL CIniEx::RemoveKey(CString Section,CString Key)
{
int nIndex=LookupSection(&Section);
if (nIndex==-1) return FALSE;
int nKeyIndex=LookupKey(nIndex,&Key);
if (nKeyIndex==-1) return FALSE;
m_Keys[nIndex]->RemoveAt(nKeyIndex);
m_Values[nIndex]->RemoveAt(nKeyIndex);
m_Changed=TRUE;
return TRUE;
}
//Removes key and it's value
BOOL CIniEx::RemoveKey(CString Key)
{
return RemoveKey("",Key);
}
//Removes given section(including all keys and values)
//return FALSE when given section not found
//It won't couse memory leak because when deleting object
//the msize (malloc size) checking
BOOL CIniEx::RemoveSection(CString Section)
{
int nIndex=LookupSection(&Section);
if (nIndex==-1) return FALSE;
m_Keys[nIndex]->RemoveAll();
m_Values[nIndex]->RemoveAll();
delete m_Keys[nIndex];
delete m_Values[nIndex];
m_Keys[nIndex]=NULL;
m_Values[nIndex]=NULL;
m_Sections.RemoveAt(nIndex);
m_SectionNo--;
m_Changed=TRUE;
return TRUE;
}
int CIniEx::CompareStrings(CString *str1, CString *str2)
{
if (m_NoCaseSensitive)
return str1->CompareNoCase(*str2);
else
return str1->Compare(*str2);
}
void CIniEx::GrowIfNecessary(void)
{
int alloctedObjectCount=_msize(m_Keys)/4;
//for first gives GrowSize
if (m_SectionNo>=alloctedObjectCount)
{
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//realloc for GrowSize
m_Keys=(CStringArray **)
realloc(m_Keys,
sizeof(CStringArray *) * (alloctedObjectCount + m_GrowSize ) );
m_Values=(CStringArray **)
realloc(m_Values,
sizeof(CStringArray *) * (alloctedObjectCount + m_GrowSize ) );
//allocated + GrowSize
//zero memory for new allocation
for (int i=0;i<m_GrowSize;i++)
{
m_Keys[m_SectionNo+i]=NULL;
m_Values[m_SectionNo+i]=NULL;
}
}
}
//copy each string (section name) because
//if sections parametter be a pointer it may clear content of member
void CIniEx::GetSections(CStringArray §ions)
{
for (int i=0;i<m_Sections.GetSize();i++)
sections.Add(m_Sections.GetAt(i));
}
void CIniEx::GetKeysInSection(CString section,CStringArray &keys)
{
int nIndex=LookupSection(§ion);
if (nIndex==-1) return;
for (int i=0;i<m_Keys[nIndex]->GetSize();i++)
{
keys.Add(m_Keys[nIndex]->GetAt(i));
}
} |
|
1
|