Creating this VCL application consists of the following steps:
- Create a project directory containing a text file to copy.
- Create a VCL Form with a button control.
- Write the code to read the string and write it to a file.
- Run the application.
To set up your project directory and a text file to copy
- Create a directory in which to store your project files.
- Using a text editor, create a simple text file and save it as from.txt in your project directory.
To create a VCL Form with a button control
- Choose FileNewOtherDelphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer is displayed.
- From the Standard page of the Tool palette, place a TButton component on the form.
- In the Object Inspector, enter CopyFile for the Caption and Name properties.
To write the copy stream procedure
- Select Button1 on the form.
- In the Object Inspector, double-click the OnClick action on the Events tab. The Code Editor displays, with the cursor in the TForm1.CopyFileClick (Delphi) or TForm1::CopyFileClick (C++) event handler block.
- For Delphi, Place the cursor before the begin reserved word; then press return. This creates a new line above the code block.
- For Delphi, insert the cursor on the new line created and type the following variable declaration:
var stream1, stream2: TStream;
For C++, enter the following variable declarations:
TStream *stream1, *stream2;
- Insert the cursor within the code block, and type the following code:
stream1 := TFileStream.Create('from.txt', fmOpenRead);
try
stream2:= TFileStream.Create('to.txt', fmCreate);
try
stream2.CopyFrom(stream1, stream1.Size);
finally
stream2.Free;
end;
finally
stream1.Free;
end;
stream1 = new TFileStream( “from.txt”, fmOpenRead );
try {
stream2 = new TFileStream( “to.txt”, fmCreate );
try {
stream2–>CopyFrom( stream1, stream1–>Size );
} __finally {
stream2–>Free();
}
} finally {
stream1–>Free();
}
To run the application
- Save your project files; then choose RunRun to build and run the application. The form displays with a button called CopyFile.
- Click CopyFile.
- Use a text editor to open the newly created file to.txt, which is located in your project directory. The contents of from.txt are copied into to.txt.