C++ Builder Tutorials

C++ Builder: read /write a text file with a component

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).

This example uses a stringlist that reads its strings from a text file. A stringlist is a non-visual component.
In the example, you can display individual strings by entering their number (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 TStrings 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, for example in the form's OnClose event.

Building the example

  1. Create a new VCL Forms application. As usual, it's best to save all the files in a new empty folder, such as \StringList.
  2. In unit1.h, declare a field named SL by adding a line under private:
    private:  // User declarations
      TStrings *SL;
  3. 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;
    Note: because in C++ \ acts as the "escape" character, we have to write \\ if we want to specify a backslash.
  4. Create an event handler for OnClose of Form1 and complete it as follows:
    void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
      delete SL;
  5. In a text editor (such as NotePad) create a text file with a few lines.
    Save it as List.txt in folder \StringList.
  6. Add three components to Form1: a TButton, a TEdit and a Tlabel.
  7. In the Object Inspector, change the property NumbersOnly to True.
  8. 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");
        Label1->Caption = SL->Strings[i];
  9. Save all and test your program.