C++Builder Tutorial: Learn To Sort A Text File On Windows With C++

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Tutorial: Learn To Sort A Text File On Windows With C++
February 15, 2021 By Yilmaz Yoru

In Для просмотра ссылки Войди или Зарегистрируйся sorting text string lines is very easy by setting Sorted property of a StringList to true. This example below sorts a given text file and saves as sorted in same name.

C++:
void sort_textfile(UnicodeString filename)
{
   auto str_list = new TStringList;
   str_list->LoadFromFile(filename);
   str_list->Sorted = true;
   str_list->SaveToFile(filename);
   str_list->Free();
}

Sorting a Text File with a Console VCL Application

  1. Create a new C++ Builder Console VCL project, Save all unit and project files into a folder. modify lines as below
Код:
#include <vcl.h>
 
void sort_textfile(UnicodeString filename)
{
   auto str_list = new TStringList;
   str_list->LoadFromFile(filename);
   str_list->Sorted = true;
   str_list->SaveToFile(filename);
   str_list->Free();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 sort_textfile("D:\\test.txt");
 return 0;
}
2. Hit F9 or press Run button to run your code.

That’s All.

Sorting a Text File with a Console FMX Application

If you want to develop on MutliDevice platforms you must create FireMonkey Project. You can do as same here in C++ Builder FMX Console Project, as below;
1. Create a new C++ Builder Console FMX project, Save all unit and project files into a folder. modify lines as below
C++:
#include <fmx.h>
 
void sort_textfile(UnicodeString filename)
{
   auto str_list = new TStringList;
   str_list->LoadFromFile(filename);
   str_list->Sorted = true;
   str_list->SaveToFile(filename);
   str_list->Free();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
 sort_textfile("D:\\test.txt");
 return 0;
}
2. Hit F9 or press Run button to run your code.

Sorting a Text File with a GUI based FMX or VCL Visual Application

If you want to use GUIs (Like Buttons, Memos, Edits, etc.) we can use OpenDialog component and a OnClick() event of a Button.

1. Create a new C++ Builder Console FMX or VCL project, Save all unit and project files into a folder. modify lines as below

2. Drag OpenDialog component on to form and a Button. Double click to button to create OnClick() event and modify it as below.

C++:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
     OpenDialog1->FileName="";
     OpenDialog1->Execute();
     if(FileExists(OpenDialog1->FileName))
     {
         sort_textfile(OpenDialog1->FileName);
     }
}
3. Add our sort_textfile() procedure above these lines or in public declarations of TForm in Unit1.h
4. Hit F9 or press Run button to run your code.

Note that file format should be in *.txt form and it will be modified after used.