Introduction to File Processing


Introduction to Files



A file is a series of bits of data that are arranged in a particular way to produce a usable document. For easy storage, location, and management, the bits are stored in a drive (such as a hard disc, a floppy disc, a compact disc, or any valid and supported type of storage). When these bits belong to a single but common entity, the group is referred to as a file. For even greater management, files can be stored in a parent object called a directory or a folder.

Since a file is a unit of storage and it stores information, it has a size which is the number of bits it contains. To manage it, a file also has a location also called a path that specifies where and/or how the file can be retrieved. Also, for better management, a file has attributes that indicate what can be done on a file or that provide specific information that the programmer or the operating system can use when dealing with the file.

File processing consists of creating, storing, and/or retrieving the contents of a file from a recognizable medium. For example, it is used to save word-processed files to a hard drive, to store a presentation on floppy disk, or to open a file from a CD-ROM. To perform file processing on VCL applications, you have four main choices, two derived from C and C++ languages, one or a few classes provided by the Visual Component Library, or use the Win32 API.


There are differences and similarities between a directory and a file. Among the differences:

  • A file is used to contain data. A directory doesn't contain data
  • A directory can contain one or more files and not vice-versa
  • A directory can contain other directories
  • A file can be moved from one directory to another. This operation is not possible vice-versa since a file cannot contain a directory

The similarities of both types are:

  • A directory or a file can be created. One of the restrictions is that two files cannot have the same name inside of the same directory. Two directories cannot have the same name inside of the same parent directory.
  • A directory or a file can be renamed. If a directory is renamed, the "path" of its file(s) changes
  • A directory or a file can be deleted. If a directory is deleted, its files are deleted also
  • A directory or a file can be moved. If a directory moves, it "carries" all of its files to the new location
  • A directory or a file can be copied. A file can be copied from one directory to another. If a directory is copied to a new location, all of its files are also copied to the new location

Characteristics of a File

In order to manage files stored in a computer, each file must be able to provide basic pieces of information about itself. This basic information is specified when the file is created but can change during the life time of a file.

To create a file, a user must first decide where it would be located: this is a requirement. A file can be located on the root drive. Alternatively, a file can be positioned inside of an existing folder. Based on security settings, a user may not be able to create a file just anywhere in the (file system of the) computer. Once the user has decided where the file would reside, there are various means of creating files that the users are trained to use. When creating a file, the user must give it a name following the rules of the operating system combined with those of the file system.

At the time of this writing, the rules for file names were on the MSDN web site at Windows Development\Windows Base Services\Files and I/O\SDK Documentation\Storage\Storage Overview\File Management\Creating, Deleting, and Maintaining Files\Naming a File (because it is a web site and not a book, its pages can change anytime).

The most fundamental piece of information a file must have is a name. Once the user has created a file, whether the file is empty or not, the operating system assigns basic pieces of information to it. Once a file is created, it can be opened, updated, modified, renamed, etc.

Introduction to Common File Dialog Boxes

Because files on a computer can be stored in various places, Microsoft Windows provides various means of creating, locating, and managing files through objects called Windows Common Dialog Boxes. Indeed, these dialog boxes are part of the operating system and are equipped with all the necessary operations pertinent to their functionality. To support this, C++Builder ships these ready-made dialog boxes so that, instead of, or before creating a new commonly used dialog box, first find out if C++Builder already provides an object that can do the job. The objects of C++Builder are highly efficient and were tested enough to be reliable. This means that whenever possible, you should use them.

To use a standard Windows dialog box, from the Dialogs tab of the Tool Palette, click the desired dialog’s button and click anywhere on the form. The position of the control on the form has no importance because it is only a representative. It will not appear when the form is running. Once the desired dialog’s icon is on the form, place a button that will be used to call the dialog. A dialog is called using the DialogName -> Execute() method. You can find out what button the user clicked when closing the dialog, and act accordingly.


VCL File Streaming



The Visual Component Library (VCL) provides various built-in classes to perform file processing. One of the classes that support file processing is named TFileStream. To perform file streaming using this class, first declare its instance using its constructor whose syntax is:

__fastcall TFileStream(const AnsiString FileName, Word Mode);

The first argument of this constructor is the name (or path) of the file you are dealing with. If the file does not exist or it cannot be accessed (opened or saved) for any reason, the compiler would throw an error and stop the action.

The second action, Mode, specifies what you are trying to do with the file.

The TFileStream class is conceptually designed to deal with the contents of one or more controls. Therefore, instead of concerning yourself with the values of controls, TFileStream would consider the changes that affect a control on behalf of the user, which mostly is its contents. When saving a file, TFileStream faithfully gets the contents of all controls as you wish and saves them in one file. If opening a file, TFileStream locates the content of each file and restores it. Based on this, TFileStream is appropriate for VCL objects and usually its files should not mixed with non-VCL controls.

Practical LearningPractical Learning: Introducing File Processing

  1. Start Embarcadero RAD Studio
  2. To create a new project, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  3. To save the project, on the Standard toolbar, click the Save All button Save All
  4. Create a new folder named StudentsGrades
  5. Save the unit as Main and save the project as Grades
  6. Change the Caption of the form to Students Grades and change its Name to frmMain
  7. From the Additional tab of the Tool Palette, add three Bevel and one Panel controls. Design them as follows:
    Students Grades
    Control Name Caption/Text Other Properties
    TBevel Bevel      
    TLabel Label   &First Name:  
    TEdit Edit edtFirstName    
    TLabel Label   &Last Name:  
    TEdit Edit edtLastName    
    TLabel Label   &Date of Birth:  
    TEdit Edit edtDateOfBirth    
    TLabel Label   &Gender:  
    TEdit Edit edtGender    
    TBevel Bevel      
    TLabel Label   &English:  
    TEdit Edit edtEnglish 0.00 Alignment: taRightJustify
    TLabel Label   &History:  
    TEdit Edit edtHistory 0.00 Alignment: taRightJustify
    TLabel Label   &Sciences:  
    TEdit Edit edtSciences 0.00 Alignment: taRightJustify
    TLabel Label   2nd L&anguage:  
    TEdit Edit edt2ndLanguage 0.00 Alignment: taRightJustify
    TLabel Label   G&eography:  
    TEdit Edit edtGeography 0.00 Alignment: taRightJustify
    TLabel Label   S&ports:  
    TEdit Edit edtSports 0.00 Alignment: taRightJustify
    TPanel Panel      
    TButton Button btnNew &New  
    TButton Button btnOpen &Open...

    TButton Button btnSave &Save

    TButton Button btnClose Close  
    Control Properties
    TOpenDialog FefaultExt: stf
    Filter: Student File (*.stf)|*.stf|All Files (*.*)|*.*
    Name: dlgOpen
    Title: Open a Student File
    TSaveDialog FefaultExt: stf
    Filter: Student File (*.stf)|*.stf|All Files (*.*)|*.*
    Name: dlgSave
    Title: Save Current Student Grades
  8. Double-click the New button and implement its OnClick event as follows:
    void __fastcall TfrmMain::btnNewClick(TObject *Sender)
    	edtFirstName->Text   = "";
    	edtLastName->Text    = "";
    	edtDateOfBirth->Text = "";
    	edtGender->Text      = "";
    	edtEnglish->Text     = "0.00";
    	edt2ndLanguage->Text = "0.00";
    	edtSciences->Text    = "0.00";
    	edtHistory->Text     = "0.00";
    	edtGeography->Text   = "0.00";
    	edtSports->Text      = "0.00";
  9. Double-click an unoccupied area on the form to access its OnCreate event and implement it as follows:
    void __fastcall TfrmMain::FormCreate(TObject *Sender)
  10. Save the project

Saving Controls Contents

In order to save the contents of controls, first declare a pointer to TFileStream using its constructor and specify where the file would be saved. You can specify this path directly in the constructor if you know exactly where the file should be located. This can be done if you are writing a program that stores the default file at a specific location and you know where the file should be saved. Otherwise, you can use the SaveDialog control to let the user specify where to save the file.

When saving a file, the Mode argument of the constructor can be passed as one of the following constants:

Write Mode Description
fmCreate If the user is saving a new file, this is used to save it as new
fmOpenWrite This is used to save a file as new. If the file was previously saved and reopened, this mode would erase its previous contents and fill it with the new data
fmOpenReadWrite If the file already existed, this can be used to save a file that has been modified. Otherwise it can be used to create a new file

When it is possible that other people or application would try accessing the same file at the same time, the following constants can be used to manage the sharing of files:

Share Mode Description
fmShareExclusive Only the current application can access the file
fmShareDenyWrite The file can be opened by other applications but they cannot modify its contents
fmShareDenyRead The file can be modified by other applications but they cannot open it
fmShareDenyNone There is no restriction on what the other applications can do with the current file

To combine these two mode for the Mode argument, you use the bitwise OR operator |.

Practical LearningPractical Learning: Saving a File

  1. Double-click the Save button to access its OnClick() event
  2. Implement the new event as follows:
    void __fastcall TfrmMain::btnSaveClick(TObject *Sender)
    	if( dlgSave->Execute() )
    		// Decalre a pointer to TFileStream
    		TFileStream *fstSave;
    		// Use the constructor of the TFileStream to create a file
    		try {
    			fstSave = new TFileStream(dlgSave->FileName, fmCreate);
    			ShowMessage(L"The file has been saved");
    			// Since the pointer was created, delete it,
    			// whether it was used or not
    			delete fstSave;
  3. Press F12 to display the form
  4. Save the application
  5. To execute, press F9
  6. Fill the form with the following values:
    Student Record
  7. Click Save
  8. In the Save dialog box, enter the file name as je and click Save
  9. Enter other values as follows:
    Student Record
  10. Click Save
  11. In the File Name, type rw
  12. Click Save
  13. Close the form and return to your programming environment

Loading Controls Contents

When saving the contents of controls using TFileStream, the file is arranged so the class can locate data for each object. Based on this, you can use TFileStream to open a file that was created with this class. To do this, once again, declare a pointer to TFileStream and initialize the file using the constructor. If you already know where the file is located, you can simply provide it to the constructor. Otherwise, you can use the Open dialog box and let the user select the file.

When opening a file, you can use one of the following modes as the Mode argument:

Read Mode Description
fmOpenRead This is used to open a file but the user cannot modify and then save it.
fmOpenReadWrite This allows opening an existing file, modifying, and saving it.

You can combine this mode with one of the above share modes using the bitwise OR operator.

Practical LearningPractical Learning: Opening a File

  1. Double-click the Open button
  2. Implement the new event as follows:
    void __fastcall TfrmMain::btnOpenClick(TObject *Sender)
    	TFileStream *fstOpen = NULL;
    	if( dlgOpen->Execute() )
    		try {
    			fstOpen = new TFileStream(dlgOpen->FileName,
    						  fmOpenRead | fmShareExclusive);
    			delete fstOpen;
  3. Press F12 to display the form
  4. Save the application
  5. To execute, press F9
  6. Click Open
  7. Locate one of the files you saved previously and select it
  8. Click Open
  9. Close the form and return to your programming environment

Home Copyright © 2010-2016, FunctionX