Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2007.09.23;
Скачать: CL | DM;

Вниз

Ini   Найти похожие ветки 

 
MultIfleX   (2007-08-28 09:10) [0]

Странноватый вопрос канечна, но мысль както появилась, вот интересно, ВыньАпи поддерживает работу с ini файлом ЛЮБЫМ образом загруженным в память? Или придётся свой парсер писать? Никто не додумывался ещё до этого?


 
Сергей М. ©   (2007-08-28 09:22) [1]


> придётся свой парсер писать? Никто не додумывался ещё до
> этого?


И вряд ли додумается)

Формат ini-файла - он и в Африке формат ini-файла.
Для работы с этим форматом ОС предоставляет ряд готовых функций, осуществляющих в т.ч. и в п.о. парсинг данных в этом формате.
Так что изобретением этого велосипеда додумается заняться разве что чудак.


 
Сергей М. ©   (2007-08-28 09:24) [2]


> ЛЮБЫМ образом загруженным в память


Что-то я пропустил слово "образом".

Тогда не оч понятно, какие "любые образы" имелись ввиду ..


 
MultIfleX   (2007-08-28 09:43) [3]


> Тогда не оч понятно, какие "любые образы" имелись ввиду
> ..


потоком, просто скопированный в блок памяти, IStream, etc...


 
Сергей М. ©   (2007-08-28 09:49) [4]

Ну судя по отсутствию в WinAPI ini-ф-ций, принимащих параметром указатель или интерфейс, действительно придется писать свой парсер.

Проще всего, думаю, будет наследовать TMemIniFile.


 
MultIfleX   (2007-08-28 10:28) [5]

Вот от этого и будим плясать ;)
ЗЫ. Если ктото уже делал, напишите сюда плиззз.


 
Сергей М. ©   (2007-08-28 12:10) [6]


> MultIfleX   (28.08.07 10:28) [5]


А что непонятно ?


 
Rial ©   (2007-08-29 02:17) [7]

{
Поиск идентификатора:
Var
    sSec    : String;
    sOldSec : String;
    sVal    : String;
...
sldSec :="";
sVal    :="";
While(FindIdent(sOldSec, "Имя поля", sSec, sVal))do begin
 ShowMessage(sVal);
 sOldsec    :=sSec;
end;

Версия 2.2.0
}

Unit RialIniFile;

Interface
Uses
    RialObject, Classes;

Type
    TSection = record
     Name   : String;
     HName  : String;
     Idents : TStringList;
    end;

    ptSection = ^TSection;

    TRialIniFile = Class (TRialObject)
     protected
      FSections : TList;
      FSorted   : Boolean;
      FLeftSym  : Char;
      FRightSym : Char;
      FDelim    : Char;

      //Уничтожение веток
      procedure DestroyIdents;
      //Установка режима сортировки
      procedure SetSorted(Const Sorted : Boolean);
      //Установка разделителя
      procedure SetDelim(Const Delim : Char);
      //Создание секции
      function AddSection(Const SectionName : String) : ptSection;
      //Сортировка веток
      procedure SortIdents;
      //Поиск секции
      function FindExistsSection(Const SectionName : String) : ptSection;
      //Сортировка заголовка
      procedure SortSections;
      //Поиск секции с возможностью создания
      function FindSection(Const SectionName : String) : ptSection;
      //Добавление значения
      procedure AddIdentValue(Const Section, Ident, Value : String);
      //Получение значения
      function GetIdentValue(Const Section, Ident, DefaultValue : String) : String;
      //Количество секций
      function GetSectionsCount : Integer;
      //Получение секции
      function GetSections(Const Index : Integer) : TStringList;
      //Получение имена секции
      function GetSectionName(Const Index : Integer) : String;
      //Установка имена секции
      procedure SetSectionName(Const Index : Integer; Const SectionName : String);

     protected
      //получить реальный размер
      function _GetSize : Cardinal; override;

     public
      constructor Create;
      destructor Destroy; override;

      procedure WriteString (Const Section, Ident : String;  Const Value : String);
      procedure WriteInteger(Const Section, Ident : String;  Const Value : Int64);
      procedure WriteFloat  (Const Section, Ident : String;  Const Value : Extended);
      procedure WriteBool   (Const Section, Ident : String;  Const Value : Boolean);

      function ReadString (Const Section, Ident : String;  Const Default : String   = ""   ) : String;
      function ReadInteger(Const Section, Ident : String;  Const Default : Int64    = 0    ) : Int64;
      function ReadFloat  (Const Section, Ident : String;  Const Default : Extended = 0.0  ) : Extended;
      function ReadBool   (Const Section, Ident : String;  Const Default : Boolean  = False) : Boolean;

      //Перевод строки в верхний регистр
      function UpperCase(Const S : String) : String;
      //Логичекий тип  -  строка
      function BoolToStr(Const B : Boolean) : String;
      //Строка  -  лгический тип
      function StrToBool(Const S : String) : Boolean;
      //Очистка
      procedure Clear;
      //Сортировка
      procedure Sort;
      //Поиск идентификатора
      function FindIdent(Const PrevSection, Ident : String; Out Section, Value : String) : Boolean;
      //Индекс секции
      function IndexOfSection(Const SectionName : String) : Integer;

      //Чтение строк секции
      function ReadSection(Const SectionName : String; Const StringList : TStringList) : Boolean;
      //Запись строк в секцию
      procedure WriteSection(Const SectionName : String; Const StringList : TStringList);

      //Созранение в список
      procedure SaveToStringList(Const StringList : TStringList);
      //Сохранение в файл
      function SaveToFile(Const FileName : String) : Boolean;
      //Загрузка из списка
      procedure LoadFromStringList(Const StringList : TStringList);
      //Загрузка из файла
      function LoadFromFile(Const FileName : String) : Boolean;

      //Флаг сортировки
      property Sorted  : Boolean read FSorted   write SetSorted;
      //Левый разделитель
      property LeftSym  : Char   read FLeftSym  write FLeftSym;
      //Правый разделитель
      property RightSym : Char   read FRightSym write FRightSym;
      //Разделитель значения
      property Delim    : Char   read FDelim    write SetDelim;
      //Количество секций
      property SectionCount : Integer read GetSectionsCount;
      //Списки секций
      property Sections[Const Index : Integer] : TStringList read GetSections;
      //Имена секций
      property SectionNames[Const Index : Integer] : String read GetSectionName write SetSectionName;

    end;

Implementation
Uses
    SysUtils;

Const
     VoidName = "";
     VoidInt  = -1;

function TRialIniFile.UpperCase(Const S : String) : String;
Var
   Ch      : Char;
   L       : Integer;
   Source  : PChar;
   Dest    : PChar;
begin
L :=Length(S);
SetLength(Result, L);
Source :=Pointer(S);
Dest   :=Pointer(Result);
While (L <> 0) do begin
 Ch :=Source^;
 Case Ch of
  "a".."z" : Dec(Ch, 32);
  "а".."я" : Dec(Ch, 32);
  "ё"      : Ch :="Ё";
 end;
 Dest^ :=Ch;
 Inc(Source);
 Inc(Dest);
 Dec(L);
end;
end;

function TRialIniFile.BoolToStr(Const B : Boolean) : String;
begin
If (B)then Result :="1"
      else Result :="0";
end;

function TRialIniFile.StrToBool(Const S : String) : Boolean;
Var
   N : Integer;
   E : Integer;
begin
Val(S, N, E);
Result :=(E = 0)and(N > 0);
end;

constructor TRialIniFile.Create;
begin
//родительский метод
Inherited Create;
FSections :=TList.Create;
FSorted   :=False;
FLeftSym  :="[";
FRightSym :="]";
FDelim    :="=";
end;

destructor TRialIniFile.Destroy;
begin
//Уничтожение веток
DestroyIdents;
//Уничтожение заголовка
FSections.Free;
//Внутренний вызов
inherited Destroy;
end;

function TRialIniFile._GetSize : Cardinal;
Var
   I : Integer;
begin
Result := (Inherited _GetSize);
For I :=0 to FSections.Count - 1 do
 With ptSection(FSections.Items[I])^ do begin
  Inc(Result, SizeOf(TSection));
  Inc(Result, Length(Name));
  Inc(Result, Length(HName));
  Inc(Result, Length(Idents.Text));
 end;
end;

procedure TRialIniFile.DestroyIdents;
Var
   I : Integer;
begin
For I :=0 to FSections.Count - 1 do
 ptSection(FSections.Items[I])^.Idents.Free;
end;

procedure TRialIniFile.Clear;
begin
//Инучтожение всех веток
DestroyIdents;
//Очистка ссылок
FSections.Clear;
end;

function TRialIniFile.AddSection(Const SectionName : String) : ptSection;
begin
New(Result);
With Result^ do begin
 Name   :=SectionName;
 HName  :=UpperCase(Name);
 Idents :=TStringList.Create;
end;
FSections.Add(Result);
If (FSorted)then
 SortSections;
end;


 
Rial ©   (2007-08-29 02:18) [8]

function TRialIniFile.FindExistsSection(Const SectionName : String) : ptSection;
Var
   I            : Integer;
   N            : Integer;
   HSectionName : String;
begin
Result :=Nil;
N :=FSections.Count;
If (N > 0)then begin
 HSectionName :=UpperCase(SectionName);
 For I :=0 to N - 1 do
  If (ptSection(FSections.Items[I])^.HName = HSectionName)then begin
   Result :=FSections.Items[I];
   Exit;
  end;
end;
end;

procedure TRialIniFile.SetSorted(Const Sorted : Boolean);
Var
   I : Integer;
begin
For I :=0 to FSections.Count - 1 do
 ptSection(FSections.Items[I])^.Idents.Sorted :=Sorted;
If(Sorted = True)and(FSorted = False)then SortSections;
FSorted :=Sorted;
end;

procedure TRialIniFile.SortIdents;
Var
   I : Integer;
begin
For I :=0 to FSections.Count - 1 do
 ptSection(FSections.Items[I])^.Idents.Sort;
end;

procedure TRialIniFile.Sort;
begin
SortIdents;
SortSections;
end;

function RialConfigCompare(Item1, Item2 : Pointer) : Integer;
Var
   ptS1 : ptSection;
   ptS2 : ptSection;
begin
ptS1 :=Item1;
ptS2 :=Item2;
If (ptS1^.HName > ptS2^.HName)then Result :=VoidInt
 else
  If (ptS1^.HName < ptS2^.HName)then Result :=1
                                else Result :=0;
end;

procedure TRialIniFile.SortSections;
begin
FSections.Sort(RialConfigCompare);
end;

function TRialIniFile.FindSection(Const SectionName : String) : ptSection;
begin
Result :=FindExistsSection(SectionName);
If (Result = Nil)then
 Result :=AddSection(SectionName);
end;

procedure TRialIniFile.AddIdentValue(Const Section, Ident, Value : String);
Var
   ptS : ptSection;
begin
ptS :=FindSection(Section);
ptS^.Idents.Values[Ident] :=Value;
end;

procedure TRialIniFile.SaveToStringList(Const StringList : TStringList);
Var
   I   : Integer;
   J   : Integer;
   N   : Integer;
   ptS : ptSection;
begin
N :=FSections.Count;
If (N > 0)then begin
 //Запись комметария
 ptS :=FindExistsSection(VoidName);
 If(ptS <> Nil)and(ptS^.Idents.Count > 0)then
  With ptS^.Idents do
   For J :=0 to Count - 1 do
    StringList.Add(Strings[J]);
 //Прочие ветки
 For I :=0 to N - 1 do begin
  ptS :=FSections.Items[I];
  If (ptS^.Idents.Count>0)and(ptS^.Name <> VoidName)then begin
   StringList.Add(FLeftSym + ptS^.Name + FRightSym);
   With ptS^.Idents do
    For J :=0 to Count - 1 do
     StringList.Add(Strings[J]);
  end; //If
 end; //For
end; //If N>0
end;

function TRialIniFile.SaveToFile(Const FileName : String) : Boolean;
Var
   SL : TStringList;
begin
Result :=False;
SL :=TStringList.Create;
Try
 SaveToStringList(SL);
 Try
  SL.SaveToFile(FileName);
 Except
  Exit;
 end;
Finally
 SL.Free;
end;
Result :=True;
end;

function TRialIniFile.GetIdentValue(Const Section, Ident, DefaultValue : String) : String;
Var
   ptS : ptSection;
begin
ptS :=FindExistsSection(Section);
If (ptS <> Nil)then begin
 Result :=ptS^.Idents.Values[Ident];
 If (Result = VoidName)then
  Result :=DefaultValue;
end else
 Result :=DefaultValue;
end;

procedure TRialIniFile.SetDelim(Const Delim : Char);
Var
   I : Integer;
begin
FDelim :=Delim;
For I :=0 to FSections.Count - 1 do
 ptSection(FSections.Items[I])^.Idents.Delimiter :=Delim;
end;

procedure TRialIniFile.LoadFromStringList(Const StringList : TStringList);
Var
   I                : Integer;
   Len              : Integer;
   Line             : String;
   ptCurrentSection : ptSection;
begin
ptCurrentSection :=FindSection(VoidName);  //В начале возможен комментарий
For I :=0 to StringList.Count - 1 do begin
 Line :=StringList.Strings[I];
 Len  :=Length(Line);
 If (Len>0)then
  If (Line[1] = FLeftSym)and(Line[Len] = FRightSym)then ptCurrentSection :=FindSection(Copy(Line, 2, Len - 2))
                                                   else ptCurrentSection.Idents.Add(Line);
end;
end;

function TRialIniFile.LoadFromFile(Const FileName : String) : Boolean;
Var
   SL : TStringList;
begin
Result :=False;
If (FileExists(FileName))then begin
 SL :=TStringList.Create;
 Try
  Try
   SL.LoadFromFile(FileName);
  Except
   Exit;
  end;
  LoadFromStringList(SL);
 Finally
  SL.Free;
 end;
 Result :=True;
end;
end;

function TRialIniFile.ReadSection(Const SectionName : String; Const StringList : TStringList) : Boolean;
Var
   ptS : ptSection;
begin
ptS :=FindExistsSection(SectionName);
If (ptS <> Nil)then begin
 StringList.Assign(ptS^.Idents);
 Result :=True;
end else
 Result :=False;
end;

procedure TRialIniFile.WriteSection(Const SectionName : String; Const StringList : TStringList);
Var
   ptS : ptSection;
   I   : Integer;
begin
ptS :=FindSection(SectionName);
For I :=0 to StringList.Count - 1 do
 ptS^.Idents.Add(StringList.Strings[I]);
end;

procedure TRialIniFile.WriteString(Const Section, Ident : String; Const Value : String);
begin
AddIdentValue(Section, Ident, Value);
end;

procedure TRialIniFile.WriteInteger(Const Section, Ident : String; Const Value : Int64);
begin
AddIdentValue(Section, Ident, IntToStr(Value));
end;

procedure TRialIniFile.WriteFloat(Const Section, Ident : String; Const Value : Extended);
begin
AddIdentValue(Section, Ident, FloatToStr(Value));
end;

procedure TRialIniFile.WriteBool(Const Section, Ident : String; Const Value : Boolean);
begin
AddIdentValue(Section, Ident, BoolToStr(Value));
end;

function TRialIniFile.ReadString(Const Section, Ident : String; Const Default : String) : String;
begin
Result :=GetIdentValue(Section, Ident, Default);
end;

function TRialIniFile.ReadInteger(Const Section, Ident : String; Const Default : Int64) : Int64;
begin
Result :=StrToInt64(GetIdentValue(Section, Ident, IntToStr(Default)));
end;

function TRialIniFile.ReadFloat(Const Section, Ident : String; Const Default : Extended) : Extended;
begin
Result :=StrToFloat(GetIdentValue(Section, Ident, FloatToStr(Default)));
end;

function TRialIniFile.ReadBool(Const Section, Ident : String; Const Default : Boolean) : Boolean;
begin
Result :=StrToBool(GetIdentValue(Section, Ident, BoolToStr(Default)));
end;

function TRialIniFile.FindIdent(Const PrevSection, Ident : String; Out Section, Value : String) : Boolean;
Var
   ptS : ptSection;
   I   : Integer;
   P   : Integer;
   S   : String;
begin
ptS :=FindExistsSection(PrevSection);
If (ptS = Nil)then P :=0
              else P :=FSections.IndexOf(ptS) + 1;
Result :=False;
For I:=P to FSections.Count - 1 do begin
 ptS :=FSections.Items[I];
 S   :=ptS^.Idents.Values[Ident];
 If (S <> VoidName)then begin
  Section :=ptS^.Name;
  Value   :=S;
  Result  :=True;
  Exit;
 end;
end;
end;

function TRialIniFile.GetSectionsCount : Integer;
begin
Result :=FSections.Count;
end;

function TRialIniFile.GetSections(Const Index : Integer) : TStringList;
begin
Result :=ptSection(FSections.Items[Index])^.Idents;
end;


 
Rial ©   (2007-08-29 02:18) [9]

procedure TRialIniFile.SetSectionName(Const Index : Integer; Const SectionName : String);
begin
With ptSection(FSections.Items[Index])^ do begin
 Name  :=SectionName;
 HName :=UpperCase(SectionName);
end;
end;

function TRialIniFile.IndexOfSection(Const SectionName : String) : Integer;
Var
   ptS : ptSection;
begin
ptS :=FindExistsSection(SectionName);
If (ptS = Nil)then Result :=VoidInt
              else Result :=FSections.IndexOf(ptS) + 1;
end;

end.

ох... стыдно мне за флуд. %)


 
grisme ©   (2007-08-29 02:29) [10]

кошмар %-) зато самописное


 
Dimaxx ©   (2007-08-30 01:03) [11]

Как это в АПИ нет ф-ций для работы с ini?? А это что по-вашему?

WritePrivateProfileString
GetPrivateProfileString
WritePrivateProfileStruct
GetPrivateProfileStruct
GetPrivateProfileInt
GetPrivateProfileSectionNames

описано в windows.pas.


 
Dimaxx ©   (2007-08-30 01:04) [12]

И незачем грузить ini в память...



Страницы: 1 вся ветка

Текущий архив: 2007.09.23;
Скачать: CL | DM;

Наверх




Память: 0.53 MB
Время: 0.032 c
4-1173803554
DevilDevil
2007-03-13 19:32
2007.09.23
Состояние скроллирования. Помогите пожалуйста.


2-1188137547
morter
2007-08-26 18:12
2007.09.23
Перехват исходящих пакетов


15-1188287010
infom
2007-08-28 11:43
2007.09.23
Не могу использовать на форме TWebBrowser в BDS 2006 !


15-1188071825
Turbouser
2007-08-25 23:57
2007.09.23
DM клиент


15-1188201729
Domkrat
2007-08-27 12:02
2007.09.23
TDateTimeEdit