StreamAdvancedRdWr (C++)

From RAD Studio XE2 Code Examples
Jump to: navigation, search

Language:

Description

This example demonstrates the use of TStreamReader's ReadBlock and DiscardBufferedData methods. ReadBlock is used to read a fixed number of characters from the reader and DiscardBufferedData is used when the underlying stream is seeked manually.

Code

void __fastcall TForm2::Button1Click(TObject *Sender)
{
        TStreamWriter* writer;
        TStreamReader* reader;
        TCharArray buffer;
 
        /* Create a writer */
        writer = new TStreamWriter("local_file.txt", false);
 
        /* Dump some data in */
        writer->WriteLine("Hello");
        writer->WriteLine("World!");
 
        /* Close the writer */
        delete writer;
 
        /* Create a reader */
        reader = new TStreamReader("local_file.txt");
 
        /* Prepare a buffer */
        buffer.set_length(5);
 
        /* Read first 5 characters */
        if (reader->ReadBlock(buffer, 0, buffer.Length) < buffer.Length)
                MessageDlg("Reading failed! Expected to read 5 characters!",
                        mtError, TMsgDlgButtons() << mbOK, 0);
 
        /* And now, seek the stream back by 5 characters */
        int byteCount = reader->CurrentEncoding->GetByteCount(buffer);
        reader->BaseStream->Seek(-1 * byteCount, soFromCurrent);
 
        /* Reset the internal data buffer, since we modified the stream position */
        reader->DiscardBufferedData();
 
        MessageDlg("The original message was:" + reader->ReadLine() +
                " " + reader->ReadLine(), mtError, TMsgDlgButtons() << mbOK, 0);
 
        delete reader;
}

Uses

Personal tools
Previous Versions