C File Processing

 

Overview

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 an application, you have various choices, including using features of from C and C++ languages. If you are using the either Win32, Borland C++ Builder, Visual C++, their libraries provide additional support for file processing.

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 this 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.

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 a GUI application, such as an application created using C++ Builder,  Visual C++, Win32, or another C++ programming environment, because applications are created in a visual development, you can let the users use the Save and Open common dialog boxes that they are used to.

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.

Writing Data to a File

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, ...);

The fprintf() function takes a few arguments depending on how it is used. The first parameter, stream, must be an instance of a FILE structure.

The second parameter, format, 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.

Here is an example of creating a file and letting the user supply data that would be saved to the file:

//---------------------------------------------------------------------------
// Program to perform file processing using the FILE structure
// Author: Jules Larson

#include <iostream>
#include <conio>
using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    	char Make[20], Model[20];
	unsigned int CarYear;
	long Mileage;

	FILE *CarInventory = fopen("cars.inv", "w");

	cout << "Enter the following pieces of information\n";
	cout << "Make:    "; gets(Make);
	cout << "Model:   "; gets(Model);
	cout << "Year:    "; cin >> CarYear;
	cout << "Mileage: "; cin >> Mileage;

	fprintf(CarInventory, "%s\n", Make);
	fprintf(CarInventory, "%s\n", Model);
	fprintf(CarInventory, "%d\n", CarYear);
	fprintf(CarInventory, "%d\n", Mileage);

	fclose(CarInventory);

	cout << "\nPress any key to continue...";
    	getch();
    	return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Reading Data From a File

If you have 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 parameter, stream, must be a valid instance of a FILE structure.

The second parameter, 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.

Here is an example that reads data saved previously:

//---------------------------------------------------------------------------
// Program to perform file processing using the FILE structure
// Author: Jules Larson

#include <iostream>
#include <conio>
using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    	char Make[20], Model[20];
	unsigned int CarYear;
	long Mileage;
/*
	FILE *CarInventory = fopen("cars.inv", "w");

	cout << "Enter the following pieces of information\n";
	cout << "Make:    "; gets(Make);
	cout << "Model:   "; gets(Model);
	cout << "Year:    "; cin >> CarYear;
	cout << "Mileage: "; cin >> Mileage;

	fprintf(CarInventory, "%s\n", Make);
	fprintf(CarInventory, "%s\n", Model);
	fprintf(CarInventory, "%d\n", CarYear);
	fprintf(CarInventory, "%d\n", Mileage);
*/

	FILE *CarInventory = fopen("cars.inv", "r+");

	fscanf(CarInventory, "%s\n", Make);
	fscanf(CarInventory, "%s\n", Model);
	fscanf(CarInventory, "%d\n", &CarYear);
	fscanf(CarInventory, "%d\n", &Mileage);

	cout << "Information about the car";
	cout << "\nMake:  " << Make;
	cout << "\nModel: " << Model;
	cout << "\nYear:  " << CarYear;
	cout << "\nMileage: " << Mileage << endl;

	fclose(CarInventory);

	cout << "\nPress any key to continue...";
    	getch();
    	return 0;
}
//---------------------------------------------------------------------------
 
 

  Copyright © 1998-2006 FunctionX, Inc.