Recent

Author Topic: [Solved] SaveToFile with TMemoryStream  (Read 644 times)

jcmontherock

  • Sr. Member
  • ****
  • Posts: 250
[Solved] SaveToFile with TMemoryStream
« on: June 15, 2024, 05:59:30 pm »
I wanted to export a MySQL table to SQL. This table contains about 500.000 rows. I tried avoiding problems with that number of rows. I created an AnsiString time to time each 2000 rows. It works fine except that at each beginning of string I get in the file some binary characters. The code is very simple:
Code: Pascal  [Select][+][-]
  1. // aStr is defined as AnsiString
  2. procedure TForm1.FormShow(Sender: TObject);
  3. begin
  4.   MStr := TMemoryStream.Create;
  5.   MStr.Position := 0;
  6.  
  7.   aStr := '-- ' + nl;
  8.   aStr += 'SET SQL_MODE=''NO_AUTO_VALUE_ON_ZERO'';' + nl;;
  9.   aStr += '-- SET AUTOCOMMIT = 0;' + nl;
  10.   aStr += '-- START TRANSACTION;' + nl;;
  11.   aStr += '-- SET time_zone = "+00:00";' + nl;
  12.   aStr += '';
  13.   aStr += '-- ---------------------------------------------------' + nl;
  14.   aStr += '-- ' + nl;
  15.         aStr += '--  File encoding is UTF8  ' + nl;
  16.   aStr += 'set character set utf8;' + nl;
  17.   aStr += '-- ---------------------------------------------------' + nl;
  18.   aStr += '-- ' + nl;
  19.  
  20.   MStr.WriteAnsiString(aStr);
  21.   MStr.Position := 0;
  22.   MStr.SaveToFile('aStrFile.sql');
  23.   MStr.Free;
  24.  
the file begins with 4 binary bytes. In that ex: 29010000. How to avoid such insertion at each WriteAnsiString ?
« Last Edit: June 16, 2024, 11:03:52 am by jcmontherock »
Windows 11 UTF8-64 - Lazarus 3.4-64 - FPC 3.2.2

Fibonacci

  • Sr. Member
  • ****
  • Posts: 453
  • Internal Error Hunter
Re: SaveToFile with TMemoryStream
« Reply #1 on: June 15, 2024, 06:10:13 pm »
WriteAnsiString writes the length of the string at the beginning, use Write or WriteBuffer

jcmontherock

  • Sr. Member
  • ****
  • Posts: 250
Re: SaveToFile with TMemoryStream
« Reply #2 on: June 15, 2024, 06:20:41 pm »
Thanks a lot. I changed: "MStr.WriteAnsiString(aStr);" to "MStr.WriteBuffer(aStr[1], Length(aStr));" and it works. In which situations do you use "WriteAnsiString" ?
« Last Edit: June 15, 2024, 06:23:14 pm by jcmontherock »
Windows 11 UTF8-64 - Lazarus 3.4-64 - FPC 3.2.2

Fibonacci

  • Sr. Member
  • ****
  • Posts: 453
  • Internal Error Hunter
Re: SaveToFile with TMemoryStream
« Reply #3 on: June 15, 2024, 06:28:10 pm »
In which situations do you use "WriteAnsiString" ?

For example, if you want to save few strings to be read later, like a config file, so later on each call to ReadAnsiString you get next string

 

TinyPortal © 2005-2018