c builder

Working with Files.

BaseCLX supports several ways of working with files. In addition to using file streams, there are several runtime library routines for performing file I/O. Both file streams and the global routines for reading from and writing to files are described in Approaches to file I/O.
In addition to input/output operations, you may want to manipulate files on disk. Support for operations on the files themselves rather than their contents is described in Manipulating files.

Note: When using CLX in cross-platform applications, remember that although the Object Pascal language is not case sensitive, the Linux operating system is. When using objects and routines that work with files, be attentive to the case of file names.

Approaches to File I/O.

There are three approaches you can take when reading from and writing to files:

The recommended approach for working with files is to use file streams. File streams are object instances of the TFileStream class used to access information in disk files. File streams are a portable and high-level approach to file I/O. Because file streams make the file handle available, this approach can be combined with the next one. The Using file streams discusses TFileStream in detail.
 You can work with files using a handle-based approach. File handles are provided by the operating system when you create or open a file to work with its contents. The SysUtils unit defines a number of file-handling routines that work with files using file handles. On Windows, these are typically wrappers around Windows API functions. Because the Delphi functions use Object Pascal syntax, and occasionally provide default parameter values, they are a convenient interface to the Windows API. Furthermore, there are corresponding versions on Linux, so you can use these routines in cross-platform applications. To use a handle-based approach, you first open a file using the FileOpen function or create a new file using the FileCreate function. Once you have the handle, use handle-based routines to work with its contents (write a line, read text, and so on).

The C runtime library and standard C++ library include a number of functions and classes for working with files. These have the advantage that they can be used in applications that do not use the VCL or CLX.

 

This is a list of key codes C++Builder using. When needing these key codes, remenber to include the in your header.

Key codes provide a symbolic representation of user key presses.

Key codes allow you to represent keyboard values for non-alphanumeric keys.Qt defines special constants for each key the user can press. These constants can then be used to refer to the keystroke in an OnKeyUp or OnKeyDown event handler.

The following table lists the  key codes defined in the Qt unit:

Virtual Key Code Corresponding key

Key_Escape Escape key
Key_Tab Tab key
Key_Backtab, Key_BackTab Backtab key
Key_Backspace, Key_BackSpace Backspace key
Key_Return Return key
Key_Enter Enter key
Key_Insert Insert key
Key_Delete Delete key
Key_Pause Pause key
Key_Print Print key
Key_SysReq SysReq key
Key_Home Home key
Key_End End key
Key_Left Left key
Key_Up Up key

Key_Right Right key
Key_Down Down key
Key_Prior  Prior key
Key_PageUp Page up key
Key_Next Next key
Key_PageDown  Page down key
Key_Shift Shift key
Key_Control CTRL key
Key_Meta Meta key (often this is the same as the Alt key)
Key_Alt Alt key
Key_CapsLock Caps Lock key
Key_NumLock Num Lock key
Key_ScrollLock Scroll Lock key
Key_F1 F1 key
Key_F2 F2 key
Key_F3 F3 key
Key_F4 F4 key

Key_F5 F5 key
Key_F6 F6 key
Key_F7 F7 key
Key_F8 F8 key
Key_F9 F9 key
Key_F10 F10 key
Key_F11 F11 key
Key_F12 F12 key
Key_F13 F13 key
Key_F14 F14 key
Key_F15 F1 key
Key_F16 F16 key
Key_F17 F17 key
Key_F18 F18 key
Key_F19 F19 key
Key_F20 F20 key
Key_F21 F21 key
Key_F22 F22 key
Key_F23 F23 key
Key_F24 F24 key
Key_F25 F25 key
Key_F26 F26 key
Key_F27 F27 key
Key_F28 F28 key
Key_F29 F29 key
Key_F30 F30 key
Key_F31 F31 key
Key_F32 F32 key

Key_F33 F33 key
Key_F34 F34 key
Key_F35 F35 key
Key_Super_L Super_L key
Key_Super_R Super_R key
Key_Menu Menu key
Key_Hyper_L Hyper_L key
Key_Hyper_R Hyper_R key
Key_Help Help key
Key_Space, Key_Any Space key
Key_Exclam Exclamation mark key (!)
Key_QuoteDbl Double quotes key( ?)
Key_NumberSign Number sign key (#)
Key_Dollar Dollar sign key ($)
Key_Percent Percent key (%)
Key_Ampersand Ampersand key (&)

Key_Apostrophe Apostrophe key
Key_ParenLeft Left parenthesis key (
Key_ParenRight Right parenthesis key )
Key_Asterisk Asterisk key (*)
Key_Plus Plus sign key (+)
Key_Comma Comma key (,)
Key_Minus Minus sign key (-)
Key_Period Period key (.)
Key_Slash Slash key (/)
Key_0 0 key (numeric keypad)
Key_1 1 key (numeric keypad)
Key_2 2 key (numeric keypad)

Key_3 3 key (numeric keypad)
Key_4 4 key (numeric keypad)
Key_5 5 key (numeric keypad)
Key_6 6 key (numeric keypad)
Key_7 7 key (numeric keypad)
Key_8 8 key (numeric keypad)
Key_9 9 key (numeric keypad)
Key_Colon Colon key (:)
Key_Semicolon Semicolon key (;)
Key_Less Less than key (<)
Key_Equal Equal to key (=)
Key_Greater Greater than key (>)
Key_Question Question mark key )

Key_At At key @
Key_A A key
Key_B B key
Key_C C key
Key_D D key
Key_E E key
Key_F F key
Key_G G key
Key_H H key
Key_I I key
Key_J J key
Key_K K key
Key_L L key
Key_M M key
Key_N N key
Key_O O key
Key_P P key
Key_Q Q key
Key_R R key
Key_S S key
Key_T T key
Key_U U key
Key_V V key
Key_W W key
Key_X X key
Key_Y Y key
Key_Z Z key
Key_BracketLeft Left bracket key ( [ )
Key_Backslash Backslash key (\)

Key_BracketRight Right bracket key (])
Key_AsciiCircum Ascii Circum key (^)
Key_Underscore Underscore key (_)
Key_QuoteLeft Left quote key (`)
Key_BraceLeft Left brace key ({)
Key_Bar Bar key (|)
Key_BraceRight Right brace key (})
Key_AsciiTilde Ascii Tilde key (~)
Key_nobreakspace No break space key
Key_exclamdown Upside down exclamation mark key
Key_cent Cent key 
Key_sterling Sterling pound key 

Key_currency Currency key
Key_yen Yen key
Key_brokenbar Broken bar key 
Key_section Section key
Key_diaeresis Diaeresis key
Key_copyright Copyright key 
Key_ordfeminine Feminine key
Key_guillemotleft Left angle quotation mark
Key_notsign Not sign key
Key_hyphen Hyphen key
Key_registered Registered key 
Key_macron Macron key

Key_degree degree key 
Key_plusminus Plus minus key 
Key_twosuperior Superscripted two key
Key_threesuperior Superscripted three key
Key_acute Acute key
Key_mu Mu key
Key_paragraph Paragraph key
Key_periodcentered Centered period key
Key_cedilla Cedilla key
Key_onesuperior Superscripted one key
Key_masculine Masculine key

Key_guillemotright Right angle quotation mark
Key_onequarter One-quarter key
Key_onehalf One-half key
Key_threequarters Three-quarters key
Key_questiondown Upside down question mark key
Key_Agrave A grave key
Key_Aacute A acute key
Key_Acircumflex A circumflex key
Key_Atilde A tilde key

Key_Adiaeresis A diaeresis key
Key_Aring A ring key
Key_AE AE key
Key_Ccedilla C cedilla key
Key_Egrave E grave key
Key_Eacute E acute key
Key_Ecircumflex E circumflex key
Key_Ediaeresis E diaeresis key
Key_Igrave I grave key
Key_Iacute I acute key
Key_Icircumflex I circumflex key

Key_Idiaeresis I diaeresis key
Key_ETH ETH key
Key_Ntilde N tilde key 
Key_Ograve O grave key
Key_Oacute O acute key
Key_Ocircumflex O circumflex key
Key_Otilde O tilde key
Key_Odiaeresis O diaeresis key
Key_multiply Multiply key
Key_Ooblique O oblique key
Key_Ugrave U grave key

Key_Uacute U acute key
Key_Ucircumflex U circumflex key 
Key_Udiaeresis U diaeresis key
Key_Yacute Y acute key
Key_ssharp S sharp key
Key_agrave a grave key
Key_aacute a acute key
Key_acircumflex a circumflex key
Key_atilde a tilde key
Key_adiaeresis a diaeresis key

Key_aring a ring key
Key_ae Ae key
Key_ccedilla c cedilla key
Key_egrave e grave key
Key_eacute e acute key
Key_ecircumflex e circumflex key
Key_ediaeresis e diaeresis key
Key_igrave i grave key
Key_iacute i acute key
Key_icircumflex i circumflex key
Key_idiaeresis i diaeresis key

Key_eth eth key
Key_ntilde n tilde key
Key_ograve o grave key
Key_oacute o acute key
Key_ocircumflex o circumflex key
Key_otilde o tilde key
Key_odiaeresis o diaeresis key
Key_division Division sign key
Key_oslash o slash key
Key_ugrave u grave key
Key_uacute u acute key

Key_ucircumflex u circumflex key
Key_udiaeresis u diaeresis key
Key_yacute y acute key
Key_thorn Thorn key
Key_ydiaeresis y diaeresis key
Key_unknown Unknown key

 

Project XXX.exe raised exception class EAccessViolation with message 'Access violation at address 40A29D24. Read of address 00CB88C4'. Process stopped. Use Step or Run to continue. When you debug your codes, you receive such an error prompt.

About an error raise "Access violation at address 40A29D24. Read of address 00CB88C4" in delphi or C++Builder. This is a typical error message raise by the system when you running your program. It means that your program has some problem you have not well handled.

This is always caused by an Illegal access to the memory. Like when you declare an object, but not allocate it in memory, then you access it, the error will raise. Let us take an example:

/*line 1*/        TStringList *pStrList;
/*line 2*/        pStrList->Add("my string one");        //This line will raise an error of "access vialotion at address xxxxxxxx".

The correct codes should be:
/*line 1*/        TStringList *pStrList;
/*line 2*/        pStrList = new TStringList;
/*line 3*/        pStrList->Add("my string one"); 
....................Some Codes Here......................
/*line n*/        delete pStrList;

Sometimes you have check your program many times and found no problems while it still raise such an error, why? I think this mainly caused by the bug of delphi or c++builder's enviroment. You could go the borland's home page to get the latest patch and update your delphi or c++builder.

After you patch your enviroment or there is no patch available while the error still be there. Well, you could check your programs if you have use a TClientDataSet component or you are just programming relative to the database. Try to proper to open the connection and remember to close it before quit the program. This is always effect to avoid the error.

Sometimes you have check your code carefully while still found no error, which can mean an advance error, check out here to use the CodeGuard to debug Project app.exe faulted with message: 'access violation at 0x40036887: read of address 0x00000010'. Process Stopped. Use Step or Run to continue .

And you may get interesting in the following error messages:
Exception class EInvalidCast with message 'Invalid class typecast' in Delphi/C++Builder programs .
Error loading type library/DLL. in delphi programs .
Error loading type library/DLL. in C++Builder Midas App .
project testjpg.exe raised exception class EJPEG with message 'JPEG error # 52' .
Error 823: I/O error on attaching DataBase in Microsoft Sql Server .

Thank you for reading the article, codes here, welcome back!(codeback) And Good Luck!

 

What is ini file?

The ini file is very useful in case when you need to store some configuration and retrieve them back to you programs. An ini file could save the information group by a logic function, call it "section". In the section, all detail data could be saved as a format of "keyname=value". Keyname means the name of a specify thing you want to store while value, that is, the value of this thing.

Let us see an example of win.ini of windows 2k under the winnt folder.

; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
[MCI Extensions.BAK]
asf=MPEGVideo
asx=MPEGVideo
ivf=MPEGVideo
m3u=MPEGVideo
mp2v=MPEGVideo
mp3=MPEGVideo
mpv2=MPEGVideo
wax=MPEGVideo
wm=MPEGVideo
wma=MPEGVideo
wmv=MPEGVideo
wvx=MPEGVideo
wmp=MPEGVideo2
wmx=MPEGVideo2

Here the [fonts],[extensions],[mci extensions],[files],[Mail],[MCI Extensions.BAK] are all the sections. While these lines:
asf=MPEGVideo
asx=MPEGVideo
ivf=MPEGVideo
are stored as an form of "name=value", so it is just the detail information.

In C++Builder, TIniFile let you to operate an ini file easily. Take an example of reading and writing configuration information of a from from and to an ini file. Create a new project in your c++builder enviroment. Add the following codes in the form's constructor and in the OnClose event handler.

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
   TIniFile *ini;
   ini = new TIniFile(ExtractFilePath(Application->ExeName) + ".ini");
   ini->WriteInteger("myForm", "Top", this->Top);
   ini->WriteInteger("myForm", "Left", this->Left);
   ini->WriteInteger("myForm", "Width", this->Width);
   ini->WriteInteger("myForm", "Height", this->Height);
   ini->WriteString ("myForm", "Caption", "My Form's Caption Could be Stored");
   ini->WriteBool("myForm", "InitMax", WindowState == wsMaximized);
   delete ini;
}

__fastcall TForm1::TForm1(TComponent *Owner) : TForm(Owner)

{
   TIniFile *ini;
   ini = new TIniFile(ExtractFilePath(Application->ExeName) + ".ini");
   Top = ini->ReadInteger("myForm", "Top", 50);
   Left = ini->ReadInteger( "myForm", "Left", 50);
   Top = ini->ReadInteger("myForm", "Width", 800);
   Left = ini->ReadInteger( "myForm", "Height", 600);
   Caption = ini->ReadString( "myForm", "Caption", "myForm" );
   ini->ReadBool("myForm", "InitMax", false ) ? WindowState = wsMaximized : WindowState = wsNormal;
   delete ini;
}

Run you program, then terminate it, open the file under the root folder of your project, you would found the ini file has been showed as the following:

[myForm]
Top=243
Left=202
Width=800
Height=600
Caption=My Form's Caption Could be Stored

Note: to test this code, you need add the "include " in the head.
InitMax=0

 

This example show you how to convert a specified icon to a bitmap. Easy way follow me. Create a new project in c++builder enviroment, put an Image, a Button and an OpenDialog control on the Form1. Rename the button1 ConvertIcon2Bitmap, then add the following codes as its OnClick event handler.

void __fastcall TForm1::ConvertIcon2BitmapClick(TObject *Sender)

{
  OpenDialog1->DefaultExt = ".ICO";
  OpenDialog1->Filter = "icons (*.ico)|*.ICO";
  OpenDialog1->Options << ofOverwritePrompt << ofFileMustExist << ofHideReadOnly;
  if (OpenDialog1->Execute())
  {
    TIcon *pIcon = new TIcon();
    try
    {
      AnsiString szBitmap;
      pIcon->LoadFromFile(OpenDialog1->FileName);
      szBitmap = ChangeFileExt(OpenDialog1->FileName,".BMP");
      Image1->Width = pIcon->Width;
      Image1->Height = pIcon->Height;
      Image1->Canvas->Draw(0,0,pIcon);

      Image1->Picture->SaveToFile(szBitmap);
      ShowMessage(OpenDialog1->FileName + "has been saved to " + szBitmap);
    }
    __finally
    {
      delete pIcon;
    }
}

Run your project to see the result and good luck!

 

Question:
I wrote a multi-tier(Midas) programs. On the client I use the SocketConnection connect to the server. I run my programs in my computer which has C++Builder installed, everything is ok, it connect to the server is very well. While when I distribute it to other client machine, it always shows "Error loading type library / DLL" error. What is the problem?

Answers and solution:
You have to copy the file midas.dll which could be found under your system's directory to the client machine's system directory. On windows 95/98, it is windows/system, on windows NT/2000/2003, it is winnt/system32 directory

Also you might have to note that what kind of database engine you are using. Pick different of dll files to distribute to your client according to the different database engine you used in your programs. The following table list could be your refference.

 

dll files
description
Idapi32.dll BDE basic library
Blw32.dll Language-driven library
Idr20009.dll Error Information Base
Fareast.bll Far Eastern languages Driver
Usa.bll American Speech-Language Driver
 
The following as needed optional
Database or component your used Dll files your should distribute
Paradox Idpdx32.dll
Dbase Iddbas32.dll
Access Iddao32.dll
Ascii Idasci32.dll
TBatchMove Idbat32.dll
Data Repostitory Iddr32.dll
ODBC Idodbc32.dll
BDE DataSet Provider DLL Idprov32.dll
SQL queries Idsql32.dll

Well, have goodluck!

 

A sample to use TStringList in C++Builder. The TStringList is very useful in some cases to manage the text list or objects.

Create a new project, put a button on your form. Double click the button, assign the following codes in its onClick event handler.

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    //Create a TStringList object and adding text list to it.
    TStringList *pList = new TStringList;
    pList->Add("Here is a sample");
    pList->Add("On how to use TStringList");
    pList->Add("We first create a new stringlist");
    pList->Add("then adding text list to it");
    pList->Add("What's the following thing?");
    pList->Add("Show the text statements one by one.");
    pList->Add("At last, we save it to a file.");
    pList->Add("under your root of partition c.");
    pList->Add("then delete this stringlist.");
    pList->Add("Thank you for visiting http://codeback.net");

    //Show the list we have stored in the pList
    for (int i = 0; i Count; i++)
        ShowMessage(pList->Strings[i]);

    //Save the list contents to a file
    pList->SaveToFile("c:\\sampleList.txt");

    //Delete the list from memory.
    delete pList;
}

The TStringList object can store not only strings, but also objects in its list. While store the object type of list, you need to use the addobject method, and you have to specify what kind of object it is when visit the list menbers. See below:

TButton *pBtn = new TButton(this);
pBtn->Caption = "list button";
pList->AddObject("my button", pBtn);
TButton *pButton = (TButton*)pList->Objects[0];
ShowMessage(pButton->Caption);
delete pBtn;

See more articles on C++Builder programs:

How to Start Program With Delphi/C++Builder? Delphi/C-Builder's Integrated Development Environment Introduction .
An example on using scanline to access bitmap pixels in C-Builder .
How to use an ini file in C++Builder .
How to convert an icon to a bitmap in C++Builder .
How to hide the 3D border of TPageControl in Delphi?
Using TBlobField and TBlobStream in C++Builder .
An example on how to use GetFormImage() and Assign() functions in C++Builder .
How to capture a web page's content and save it to an image .

 

Sometimes you need to make the webpages editalbe in your programs. Microsoft have supply a component webbrowser to do this. In c++builder, you could use this component TCppWebbrowser easily.

The function are:

IHTMLDocument2::put_designMode(L"On");//Open the design mode(edit mode)  
IHTMLDocument2::put_designMode(L"Off");//Close the design mode 

For detail, see the below steps.

1. Create a new project in c++builder platform.

2. Drag a CppWebbrowser onto the form from the tab internet toolbar, renamed it to "web".

3. Double click the onDocumentComplete events, adding the following codes.

void __fastcall TForm1::webDocumentComplete(TObject *Sender,
      LPDISPATCH pDisp, Variant *URL)
{
    IHTMLDocument2* doc;    //This interface is defined in mshtml.h

    HRESULT hr;
    hr = web->Document->QueryInterface(IID_IHTMLDocument2,(void**)&doc);
    if(SUCCEEDED(hr))
    {
        doc->put_designMode(L"On");
        doc->Release();            //Release the object

    }
}
 

4. Put a botton on the form, adding the following codes in its onclick event

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    web->Navigate(L"http://codeback.net");

Now, run your program. Click the button1, do you find the page is editable?

Notice: you have to include this line in your file header, #include "mshtml.h".

If you are using Delphi, and want to make the TWebBrowser editable in Delphi, see this article Use the TWebBrowser as an html editor in delphi .

 
2
Next
End