StringReaderWriter (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the TStringReader and TStringWriter classes.

Code

void __fastcall TMainForm::btReadClick(TObject *Sender)
{
  Char Ch;
  TStringReader* Reader1;
  TStringReader* Reader2;
  TCharArray Buffer;
  String Line;
  String Init;

  Init = String("This is the first line") + char(13) + "This is the some text";

  /* Create a string reader. */
  Reader1 = new TStringReader(Init);
  Reader2 = new TStringReader(Init);

  /* Read the first string. */
  Edit1->Text = Reader1->ReadLine();
  Memo1->Text = Reader1->ReadToEnd();

  /* Prepare a buffer. */
  Buffer.set_length(23);

  /* Read first 23 characters from the second string. */
  if (Reader2->ReadBlock(Buffer,0,Buffer.Length) < Buffer.Length)
  {
	MessageDlg("Reading failed! Expected to read 23 characters!",
	  mtError, TMsgDlgButtons() << mbOK, 0);
  }

  /* Read the rest of the second string, char-by-char, and write it in the
     second memo box. */
  Line = "";
  do
  {
	  Ch = Char(Reader2->Read());
	  Line += Ch;
  }
  while (Reader2->Peek() >= 0);
  Memo2->Text = Line;

  /* Close the reader. */
  Reader1->Close();
  Reader2->Close();
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::btWriteClick(TObject *Sender)
{
  TStringWriter* Writer;
  String MyStr;

  /* Create a string writer. */
  Writer = new TStringWriter();

  /* Store the text in the writer. */
  Writer->WriteLine(Edit1->Text);
  Writer->Write(Memo1->Text + sLineBreak + Memo2->Text);
  MyStr = Writer->ToString();
  ShowMessage(MyStr);

  /* Clear writer's buffer data. */
  Writer->Flush();

  /* Close the writer. */
  Writer->Close();
  delete Writer;
}

Uses