如何从INI文件中存储和读取数组?

3

我如何将某些东西的数组写入一个ini文件中的一个标识符中,最近我又如何从中读取并将值存储在数组中?

以下是我希望ini文件看起来的样子:

[TestSection]
val1 = 1,2,3,4,5,6,7

我遇到的问题:

  1. 我不知道我需要使用哪些函数
  2. 大小不是静态的。它可能超过7个值,也可能少于7个。我如何检查长度?
2个回答

13

您不需要长度说明符。分隔符清楚地限定了数组的部分。

如果您在INI文件中定义了如下部分:

[TestSection]
val1 = 1,2,3,4,5,6,7

那么你需要做的就是

procedure TForm1.ReadFromIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;
    SL.CommaText := FINiFile.ReadString('TestSection', 'Val1', '');
    SetLength(MyArray, SL.Count);

    for I := 0 to SL.Count - 1 do
      MyArray[I] := StrToInt(Trim(SL[I]))
  finally
    SL.Free;
  end;
end;

procedure TForm1.WriteToIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;

    for I := 0 to Length(MyArray) - 1 do
      SL.Add(IntToStr(MyArray[I]));

    FINiFile.WriteString('TestSection', 'Val1', SL.CommaText);
  finally
    SL.Free;
  end;
end;

呵呵,Re0sless 有点更快 :) - Runner

12

你可以像这样做:

uses inifiles

procedure ReadINIfile
var
  IniFile : TIniFile;
  MyList:TStringList;
begin
    MyList  := TStringList.Create();
    try 
        MyList.Add(IntToStr(1));
        MyList.Add(IntToStr(2));
        MyList.Add(IntToStr(3));


        IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
        try               
            //write to the file 
            IniFile.WriteString('TestSection','Val1',MyList.commaText);

            //read from the file
            MyList.commaText  := IniFile.ReadString('TestSection','Val1','');


            //show results
            showMessage('Found ' + intToStr(MyList.count) + ' items ' 
                            + MyList.commaText);
        finally
            IniFile.Free;
        end;
    finally
        FreeAndNil(MyList);
   end;

end;

由于没有内置函数可以将数组直接保存到ini文件中,因此您需要将整数以CSV字符串的形式保存和加载。


1
请注意,数组中的多余空格会导致错误。 - Jim McKeeth
@JimMcKeeth,你可以将StrictDelimiter设置为true。这样就不会有问题了。 - Jeppe Clausen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接