Home

C File Processing

 

C How To Process Files

File processing is traditionally performed using the FILE class. In the strict C sense, FILE is a structure and it is defined in the stdio.h header file. This object is equipped with variables used to indicate what operation would be performed. To use this structure, you can first declare an instance of the FILE structure. Here is an example:

FILE *Starter;

After instantiating the structure, you can define what to do with it, using one of the provided functions. Because FILE was created as a C structure, it does not have member functions. The functions used to perform its related operations on files are also declared in the stdio.h header file.

Practical Learning Practical Learning: Preparing for File Processing

  1. Start a new application with its default form
  2. To save the project, on the Standard toolbar, click the Save All button
  3. Create a new folder named Students Grades
  4. Save the unit as Main and save the project as Grades
  5. Change the Caption of the form to Students Grades and change its Name to frmMain
  6. From the Additional tab of the Component Palette, add three Bevel and one Panel controls. Design them as follows:
     
  7. From the Standard tab of the Component Palette, add the Labels, one ComboBox, and Edit controls as follows:
     
  8. Name the Edit and the ComboBox controls after their accompanying labels: edtFirstName, edtMI, edtLastName, edtDOB, cboGender, edtEnglish, edt2ndLanguage, edtHistory, edtGeography, edtSciences, and edtSports
  9. On the form, click the combo box and, in the Object Inspector, double-click the right field of its Items property
  10. Add three lines as Unknown, Male, and Female
  11. Click OK
  12. From the Additional tab of the Component Palette, click the BitBtn control and click in the top Bevel.
  13. Change its properties as follows:
    Caption = &New
    Glyph = New2
    Name = btnNew
  14. Double-click the New button and implement its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnNewClick(TObject *Sender)
    {
        edtFirstName->Text   = "";
        edtMI->Text          = "";
        edtLastName->Text    = "";
        edtDOB->Text         = "";
        cboGender->ItemIndex = 0;
        edtEnglish->Text     = "0.00";
        edt2ndLanguage->Text = "0.00";
        edtHistory->Text     = "0.00";
        edtGeography->Text   = "0.00";
        edtSciences->Text    = "0.00";
        edtSports->Text      = "0.00";
    }
    //---------------------------------------------------------------------------
  15. Double-click an unoccupied area on the form to access its OnCreate event and implement it as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::FormCreate(TObject *Sender)
    {
        btnNewClick(Sender);
    }
    //---------------------------------------------------------------------------
  16. Save the project

 

Opening and/or Saving Files

To create a new file, open an existing file, or save a file, you use the fopen() function. Its syntax is:

FILE *fopen(const char *FileName, const char *Mode);

The first argument, FileName, must be a valid name of a file. If the user is creating or saving a new file, you can let him specify the name of the file, following the rules of the operating system. If the user is opening an existing file, you can make sure the file really exists, retrieve its name and pass it to the fopen() function.

Because the fopen() function is used to save a new file, to open an existing one, or to save a file that was only modified, the second argument, Mode, actually allows you to decide what operation the function will be used to perform. This argument is a short string of one or two characters and can be one of the following:

Mode Role If the file already exists If the file does not exist
r Opens an existing file for reading only. it would be opened and can be read. After the file is opened, the user cannot add data to it. the operation would fail.
w Saves a new file. the file's contents would be deleted and replaced by the new content. a new file is created  and can be written to.
a Opens an existing file, saves new file, or saves a existing file that has been modified. the file is opened and can be modified or updated. New information written to the file would be added to the end of the file. a new file is created  and can be written to.
r+ Opens an existing file. the file is opened and its existing data can be modified or updated. the operation would fail.
w+ Creates new file or saves an existing one. the file is opened, its contents would be deleted and replaced with the new contents. a new file is created  and can be written to.
a+ Creates a new file or modifies an existing one. it is opened and its contents can be updated. New information written to the file would be added to the end of the file. a new file is created  and can be written to.

If the operation performed using the fopen() function is successful, the function returns a pointer to the FILE instance that was declared. The FILE structure is usually used in C and C++ console programs that must conform to console applications. However, when used in VCL applications, because applications are created in a visual development, you should let the users use the Save and Open common dialog boxes that they are used to. In this case, if the user is opening a file, you can pass the FileName member variable of the common dialog box to the fopen() function. Because the fopen() function takes a pointer to char while the Save and Open dialog boxes use AnsiString members, you should convert The TOpenDialog::FileName or the TSaveDialog::FileName to a C string.

After using a file, you should/must close its stream. This is done using the fclose() function. Its syntax is:

int fclose(FILE *stream);

To use this function, you must let it know what instance of the FILE object you are closing.

Practical Learning Practical Learning: Opening and Saving Files

  1. From the Dialogs tab of the Component Palette, click the OpenDialog button and click anywhere in the form
  2. On the Object Inspector, change its DefaultExt to rcd
  3. In its Filter field, type
    Student Record (*.rcd)|*.rcd|All Files
  4. From the Dialogs tab of the Component Palette, click the SaveDialog button and click anywhere in the form
  5. On the Object Inspector, change its DefaultExt to rcd and, in its Filter field, type
    Student Record (*.rcd)|*.rcd|All Files
     
  6. On the top section of the Main.cpp file, include the stdio library file as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #include <cstdio>
    using namespace std;
    #pragma hdrstop
    
    #include "Main.h"
    //---------------------------------------------------------------------------
  7. To perform the opening of a record, on the form, double-click the Open button and implement its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnOpenClick(TObject *Sender)
    {
    	FILE *FOpen;
    
    	if( OpenDialog1->Execute() )
    	{
    		FOpen = fopen(OpenDialog1->FileName.c_str(), "r+");
    
    		if( FOpen == NULL )
    		{
    			ShowMessage("The file could not be opened");
    			return;
    		}
    	}
    
    	fclose(FOpen);
    }
    //---------------------------------------------------------------------------
  8. To perform the saving of a record, on the form, double-click the Save button and implement its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnSaveClick(TObject *Sender)
    {
    	FILE *FSave;
    
    	if( SaveDialog1->Execute() )
    	{
    		FSave = fopen(SaveDialog1->FileName.c_str(), "w");
    
    		if( FSave == NULL )
    		{
    			ShowMessage("The file could not be saved");
    			return;
    		}
    	}
    
    	fclose(FSave);
    }
    //---------------------------------------------------------------------------
  9. Save the project

Reading From and Writing to Files

To save a file, you must write data to its contents. This operation is performed using the fprintf() or the fwprintf() functions. Their syntaxes are:

int fprintf(FILE *stream, const char *format, ...);
int fwprintf(FILE *stream, const wchar_t *format, ...);

Each one of these functions takes a few arguments depending on how it is used. The first argument, stream, must be an instance of a FILE structure.

The second argument is a string that specifies how data will be formatted and possibly positioned in the stream instance.The string typically starts with the % symbol followed by one or more characters that represents a format. Different formats are used depending on the type of data of the variable that is being written. You can use one the following characters:

Character Used for
c A single character
d An integer
e A floating-point number
f A floating-point number
g A floating-point number
h A short integer
i A decimal, a hexadecimal, or an octal integer
o An octal integer
s A string followed by a white space character
u An unsigned decimal integer
x A hexadecimal integer

After specifying the format, you can type the name of the variable that is being saved. You can repeatedly use the fprintf() function for each variable you want to save. If you have opened a file and want to retrieve data stored from it, you can use the fscanf() or the fwscanf() function. Their syntaxes are:

int fscanf(FILE *stream, const char *format[, address, ...]);
int fwscanf(FILE *stream, const wchar_t *format[, address, ...]);

The first argument, stream, must be a valid instance of a FILE structure. The second argument, format, follows the same rules as for the fprintf() and the fwprintf() functions. After typing the format, type the name of the variable that is being retrieved.

Practical Learning Practical Learning: Reading to and Writing From Files

  1. In the Main.cpp file, change the OnClick event of the Open button as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnOpenClick(TObject *Sender)
    {
    	FILE *FOpen; 
    
    	char FirstName[30], LastName[30], DOB[40];
    	int Gender;
    	char English[6], Language2[6], History[6],
    	Geography[6], Sciences[6], Sports[6];
    
    	if( OpenDialog1->Execute() )
    	{
    		FOpen = fopen(OpenDialog1->FileName.c_str(), "r+");
    
    		if( FOpen == NULL )
    		{
    			ShowMessage("The file could not be opened");
    			return;
    		}
    
    		fscanf(FOpen, "%s", FirstName);
    		fscanf(FOpen, "%s", LastName);
    		fscanf(FOpen, "%s", DOB);
    		fscanf(FOpen, "%d", &Gender);
    		fscanf(FOpen, "%s", English);
    		fscanf(FOpen, "%s", Language2);
    		fscanf(FOpen, "%s", History);
    		fscanf(FOpen, "%s", Geography);
    		fscanf(FOpen, "%s", Sciences);
    		fscanf(FOpen, "%s", Sports);
    
    		edtFirstName->Text = FirstName;
    		edtLastName->Text = LastName;
    		edtDOB->Text = DOB;
    		cboGender->ItemIndex = Gender;
    		edtEnglish->Text = English;
    		edt2ndLanguage->Text = Language2;
    		edtHistory->Text = History;
    		edtGeography->Text = Geography;
    		edtSciences->Text = Sciences;
    		edtSports->Text = Sports;
    	}
    
    	fclose(FOpen);
    }
    //---------------------------------------------------------------------------
  2. In the Main.cpp file, change the OnClick event of the Save button as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnSaveClick(TObject *Sender)
    {
    	FILE *FSave;
    
    	char FirstName[30], LastName[30], DOB[40];
    	int Gender;
    	double English, Language2, History, Geography, Sciences, Sports;
    
    	strcpy(FirstName, edtFirstName->Text.c_str());
    	strcpy(LastName, edtLastName->Text.c_str());
    	strcpy(DOB, edtDOB->Text.c_str());
    	Gender = cboGender->ItemIndex;
    
    	English = StrToFloat(edtEnglish->Text);
    	Language2 = StrToFloat(edt2ndLanguage->Text);
    	History = StrToFloat(edtHistory->Text);
    	Geography = StrToFloat(edtGeography->Text);
    	Sciences = StrToFloat(edtSciences->Text);
    	Sports = StrToFloat(edtSports->Text);
    
    	if( SaveDialog1->Execute() )
    	{
    		FSave = fopen(SaveDialog1->FileName.c_str(), "w");
    
    		if( FSave == NULL )
    		{
    			ShowMessage("The file could not be opened");
    			return;
    		}
    
    		fprintf(FSave, "%s\n", FirstName);
    		fprintf(FSave, "%s\n", LastName);
    		fprintf(FSave, "%s\n", DOB);
    		fprintf(FSave, "%d\n", Gender);
    		fprintf(FSave, "%.2f\n", English);
    		fprintf(FSave, "%.2f\n", Language2);
    		fprintf(FSave, "%.2f\n", History);
    		fprintf(FSave, "%.2f\n", Geography);
    		fprintf(FSave, "%.2f\n", Sciences);
    		fprintf(FSave, "%.2f\n", Sports);
    	}
    
    	fclose(FSave);
    }
    //---------------------------------------------------------------------------
  3. Save and test the application
     
  4. After using it, close it and return to Bcb
Home Copyright 2005-2007 FunctionX, Inc.