Delphi中使用Ini檔案是非常友善的,很簡單的就可以操作一個Ini檔案。但是也存在着局限性,比如TIniFile的ReadString函數
最大隻能讀2047個字元,超過了的則讀不出來,鑒于這個,很容易的修改,可以找到其ReadString函數,擴大其緩沖區則可。
同時還有一點不足之處就是,不能寫入流。寫入流有的時候,用處也是非常大的了。但是Ini檔案卻沒有提供該函數,進日由于
工作中需要用到這樣的東西,于是想了一個辦法能夠在Ini檔案中讀寫流資料。發來與大家分享一下。
其實寫入流資料也是輸入字元串。衆所周知,Ini檔案中輸入的字元串不能換行,否則換行後的字元串則成一個非有效的值了。
是以,把流資料當字元串輸入的時候,就要防止其有換行符号,于是想到一個辦法,先把他變成16進制字元串,然後在寫入
這樣就防止了換行。讀出來,也就把16進制字元串再轉換成二進制資料。
是以就需要如下幾個函數了:
- Function StreamToStr(Value: TStream): String; //流轉化成16進制字元串
- Function StrToStream(Const aStr: String; Value: TStream): Integer;//16進制字元串化為流資料
- Function ReadStream(Const Section,aParamName: String; aValue: TStream): Integer;//讀取流
- Procedure WriteStream(Const Section,aParamName: String; aValue: TStream);//寫入流
- function TIniFile.StreamToStr(Value: TStream): String;
- begin
- result := PointToHex(TMemoryStream(Value).memory,Value.Size); //該函數我以前有寫過,請看以前的文章
- end;
- function TIniFile.StrToStream(const aStr: String;
- Value: TStream): Integer;
- Var
- Text: String;
- Stream: TMemoryStream;
- Pos: Integer;
- Begin
- Text := aStr;
- If Text <> '' Then
- Begin
- If Value Is TMemoryStream Then
- Stream := TMemoryStream(Value)
- Else
- Stream := TMemoryStream.Create;
- Try
- Pos := Stream.Position;
- Stream.SetSize(Stream.Size + Length(Text) Div 2);
- //轉換成二進制流資料,看以前的文章
- HexToBin(Text, Pointer(Integer(Stream.Memory) + Stream.Position), Length(Text) Div 2);
- Stream.Position := Pos;
- If Value <> Stream Then Value.CopyFrom(Stream, Length(Text) Div 2);
- Result := Stream.Size - Pos;
- Finally
- If Value <> Stream Then Stream.Free;
- End;
- End
- Else
- Result := 0;
- end;
- function TIniFile.ReadStream(const Section, aParamName: String;
- aValue: TStream): Integer;
- Var
- mValue: String;
- begin
- mValue := ReadString(Section,aParamName, '');
- Result := StrToStream(mValue, aValue);
- end;
- procedure TIniFile.WriteStream(const Section, aParamName: String;
- aValue: TStream);
- Var
- mValue: String;
- Begin
- mValue := StreamToStr(aValue);
- WriteString(Section,aParamName, mValue);
- end;