开发者

How can I separate the sections in an INI file?

When saving to an INI file, especially when more than one section is defined, the data is saved all together with no lines between the sections.

For external editing purposes it would be handy to separate each secti开发者_JAVA技巧on with a line break, to make it easier to view and edit the INI file.

For Example:

Standard Ini

[GENERAL]
value1=0
value2=somestring
[ADVANCED]
type=1
autosave=0
[OTHER]
showatstartup=1

Ini with seperating lines

[GENERAL]
value1=0
value2=somestring

[ADVANCED]
type=1
autosave=0

[OTHER]
showatstartup=1

How can this be done?


The easiest way would be to open the .ini file using TMemIniFile instead of TIniFile. It works the same way, but when it saves (UpdateFile), spaces are automatically added between sections.


Load the file and insert empty lines before each section name. Here's a function for it:

procedure InsertSectionLineBreaks(const IniFile: TFileName);
var
  f: TStrings;
  i: Integer;
begin
  f := TStringList.Create;
  try
    f.LoadFromFile(IniFile);
    for i := Pred(f.Count) downto 1 do
      if (f[i] <> '') and (f[i][1] = '[') then
        f.Insert(i, '');
    f.SaveToFile(IniFile);
  finally
    f.Free;
  end;
end;

Note that if there is already an empty line before the section name, this code will add another one. The loop goes down to one instead of zero assuming we don't need to add an empty line above the first section in the file.


Manually adding in the lines is indeed a workable solution. Another option is to create your own custom class inheriting from TIniFile and alter the behavior to include an extra line break before the section header.

Update: Use TCustomIniFile as the base class if you want to use this approach, not TIniFile.


Why not use simple carriage return: Add(#13#10);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜