C++ Builder Tutorial: TStringList load from / write to file
You can read from / write to a text file with list components such as TMemo, TListBox, and so on. This is done
with the functions LoadFromFile and SaveToFile, for example:
Memo1->Lines->LoadFromFile(ATextFile);
Instead, in our example we'll use a TStringList object that reads its strings from a text file.
A stringlist is a non-visual component.
We want to display individual strings by entering their "index" and clicking a button.
Because the stringlist must be available at any time, we have to construct it at start-up and destroy it before
the application terminates:
- In the unit file for the application's main form, there must be a field of type TStringList in the form's declaration.
In our example, a field called SL.
- An event handler for the main form's OnCreate event (executes before the form appears) should create a stringlist
and assign it to the field that was declared earlier.
- The stringlist must be destroyed before the application terminates, i.e. in the form's OnDestroy event.
Building the example
- Create a new VCL Forms application. As usual, it's best to save all the files in a new empty folder,
such as \StringList.
- In unit1.h, declare a field named SL by adding a line under private:
private: // User declarations
TStringList *SL;
- Through the Object Inspector, create an event handler for OnCreate of Form1 and complete it as follows:
void __fastcall TForm1::FormCreate(TObject *Sender)
{
SL = new TStringList;
SL->LoadFromFile("C:\\StringList\\List.txt");
}
Note: because in C++ the symbol \ acts as the "escape" character, we have to write \\ if we want to specify a backslash.
- Create an event handler for the OnClose event of Form1 and complete it as follows:
void __fastcall TForm1::FormDestroy(TObject *Sender, TCloseAction &Action)
{
delete SL; // destroy the stringlist before the program terminates
}
- In a text editor (such as NotePad) create a text file with a few lines.
Save it as List.txt in folder \StringList.
- Add three components to Form1: a TButton, a TEdit and a Tlabel.
- Set the Text property of Edit1 to 0.
Change the property NumbersOnly to True.
- Double click Button1 and complete the event handler as follows:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
int i;
i = StrToInt(Edit1->Text);
if (i > SL->Count)
ShowMessage("Line does not exist");
else
Label1->Caption = SL->Strings[i];
}
- Save all and test your program.
You can also write a text file by using the TStringList's SaveToFile() method:
SL->SaveToFile("C:\\StringList\\List2.txt");
|
|