天天看點

向Ini檔案中寫入流資料

 Delphi中使用Ini檔案是非常友善的,很簡單的就可以操作一個Ini檔案。但是也存在着局限性,比如TIniFile的ReadString函數

最大隻能讀2047個字元,超過了的則讀不出來,鑒于這個,很容易的修改,可以找到其ReadString函數,擴大其緩沖區則可。

同時還有一點不足之處就是,不能寫入流。寫入流有的時候,用處也是非常大的了。但是Ini檔案卻沒有提供該函數,進日由于

工作中需要用到這樣的東西,于是想了一個辦法能夠在Ini檔案中讀寫流資料。發來與大家分享一下。

其實寫入流資料也是輸入字元串。衆所周知,Ini檔案中輸入的字元串不能換行,否則換行後的字元串則成一個非有效的值了。

是以,把流資料當字元串輸入的時候,就要防止其有換行符号,于是想到一個辦法,先把他變成16進制字元串,然後在寫入

這樣就防止了換行。讀出來,也就把16進制字元串再轉換成二進制資料。

是以就需要如下幾個函數了:

  1. Function StreamToStr(Value: TStream): String; //流轉化成16進制字元串
  2. Function StrToStream(Const aStr: String; Value: TStream): Integer;//16進制字元串化為流資料
  3. Function ReadStream(Const Section,aParamName: String; aValue: TStream): Integer;//讀取流
  4. Procedure WriteStream(Const Section,aParamName: String; aValue: TStream);//寫入流
  5. function TIniFile.StreamToStr(Value: TStream): String;
  6. begin
  7.   result := PointToHex(TMemoryStream(Value).memory,Value.Size); //該函數我以前有寫過,請看以前的文章
  8. end;
  9. function TIniFile.StrToStream(const aStr: String;
  10.   Value: TStream): Integer;
  11. Var
  12.   Text: String;
  13.   Stream: TMemoryStream;
  14.   Pos: Integer;
  15. Begin
  16.   Text := aStr;
  17.   If Text <> '' Then
  18.   Begin
  19.     If Value Is TMemoryStream Then
  20.       Stream := TMemoryStream(Value)
  21.     Else
  22.       Stream := TMemoryStream.Create;
  23.     Try
  24.       Pos := Stream.Position;
  25.       Stream.SetSize(Stream.Size + Length(Text) Div 2);
  26.       //轉換成二進制流資料,看以前的文章     
  27.       HexToBin(Text, Pointer(Integer(Stream.Memory) + Stream.Position), Length(Text) Div 2);     
  28.       Stream.Position := Pos;
  29.       If Value <> Stream Then Value.CopyFrom(Stream, Length(Text) Div 2);
  30.       Result := Stream.Size - Pos;
  31.     Finally
  32.       If Value <> Stream Then Stream.Free;
  33.     End;
  34.   End
  35.   Else
  36.     Result := 0;
  37. end;
  38. function TIniFile.ReadStream(const Section, aParamName: String;
  39.   aValue: TStream): Integer;
  40. Var
  41.   mValue: String;  
  42. begin
  43.   mValue := ReadString(Section,aParamName, '');
  44.   Result := StrToStream(mValue, aValue);
  45. end;
  46. procedure TIniFile.WriteStream(const Section, aParamName: String;
  47.   aValue: TStream);
  48. Var
  49.   mValue: String;
  50. Begin
  51.   mValue := StreamToStr(aValue);
  52.   WriteString(Section,aParamName, mValue);
  53. end;

繼續閱讀