C++ Tutorial: Simple Text viewer
Submitted by Bright777 on Tuesday, February 25, 2014 - 19:13.
The program for today is text viewer. It works this way – you click on a button, then you choose a file with *.txt extension, after that you click “Open” and you can see all file in your main form. For coding this program we will use Borland C++ Builder 6.
Preparation
First of all create new application. On the main form put such controls as Button, Rich Edit control and OpenFile Dialog. After you have done that you need to configure properties of Rich Edit control. Go property called “Lines”, click on button with ‘…’ and delete all lines. In such way we make clear control by default. Second you need to do is to go to ScrollBars property and choose ssVertical value. This action enables vertical scroll bar in your Rich Edit control than the text is too big and is out of borders.
Code
After you have done with preparation you need to code Button click event. Just double click on the button and then you will see a code window. In this window you need to paste the code below:
In this code we use Win API. In the first line we dynamically declare a handle to our operation of opening the file. Later we declare dword variable and a char array for buffer. In this buffer we will put text from the file. Then our dialog has executed and we have chosen the file to open use CreateFile function to find the file and fill the handle. Later we use that handle to open the file, copy information in buffer and after that – in the rich edit component.
Thanks
- void __fastcall TForm1::Button1Click(TObject *Sender)
- {
- HANDLE hOpen=new HANDLE;
- DWORD buf1=0;
- char buf[10000]="";
- if( OpenDialog1->Execute())
- {
- hOpen=CreateFile(OpenDialog1->FileName.c_str(),GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
- ReadFile(hOpen,buf,10000,&buf1,NULL);
- }
- RichEdit1->Lines->Add(buf);
- }
Add new comment
- 162 views