Chapter 10

 

Files (1st Note)

 

Information is stored on the auxiliary memory device in the form of a data file. Thus data file allows us to store information permanently, and to access and alter that information whenever necessary.

In C, extensive set of library functions is available for creating and processing data files. Unlike other programming languages, C does not distinguish between sequential and direct access (random access) data files. There are two different types of data files, called stream oriented data files, and system oriented data files. Thus, disk input/output functions can be divided into two categories:

 

(a)   High level I/O functions (also called standard I/O or stream I/O functions)

(b)  Low level file I/O functions (also called system I/O functions)

 

High level disk I/O functions are more commonly used in C programs, since they are easier to use then low level disk I/O functions. There is one basic difference between high level and low level disk I/O functions. High level disk I/O functions do their own buffer management, whereas in low level disk I/O functions, buffer management has to be done explicitly by the programmer.

Low level disk I/O is harder to program than high level disk I/O. however, low level disk I/O is more efficient both in terms of operation and the amount of memory used by the program. The following figure shows the detailed classification of disk I/O functions.

 



Working with text file

When working with a stream-oriented data file, the first step is to establish the buffer area, where information is temporarily stored while being transferred between the computer’s memory and the data file. The buffer area allows information to be read from and or written to the data file more rapidly than would otherwise possible. The buffer area is established by writing

            FILE *ptvar;

Where FILE is a special structure type that establishes the buffer area and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type FILE is defined within a system include file, typically stdio.h. The pointer ptvar is often referred to as a stream pointer, or simply a stream.

A data file must be opened before it can be created or processed. This associates the file name with the buffer area (i.e., with the stream). It also specifies how the data file will be utilized, i.e., as a read-only file, a write-only file, or a read/write file, in which both operation are permitted.

The library function fopen is used to open a file. This function is typically written as

            ptvar=  fopen(file-name, file-type);

Where file-name and file-type are strings that represent the name of the data file and the manner in which the data file will be utilized.

Each file we open will have its own FILE structure. The FILE structure contains information about the file being used, such as its current size, its location in memory etc. More importantly it contains a character pointer which points to the character that is about to get read.

Closing The File

When we have finished reading from the file, we need to close it. This is done using the function fclose() through the statement,

fclose(fp);

 

File Opening Modes

Following is a list of all possible modes in which a file can be opened. The tasks performed by fopen() when a file is opened in each is these modes are also mentioned below.

 

“r”       Searches file. If the file exists loads if into memory and sets up a pointer, which points to the first character in it. If the file doesn’t exist it returns NULL.

           

            Operations possible – reading from the file.

 

“w”      Search file. If the file exists, its contents are overwritten. If the file doesn’t exit, a new file is created. Returns NULL, if unable to open file

           

Operation possible – writing to the file.

 

“a”       Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it the file doesn’t exist, a new file is crated. Returns NULL, if unable to open file.

 

            Operations possible – appending new contents at the end of file.

 

 

 

“r+”     Searches file. If it exists loads it into memory and sets up a pointer, which points to the first character in it. If file doesn’t exist it returns NULL.

           

            Operations possible – reading existing contents, writing new contents, modifying existing contents of the file.

 

“w+”   Search file. Of the file exists, its contents are destroyed. If the file doesn’t exit a new file is created. Returns NULL, if unable to open file.

 

            Operations possible – writing new contents,  reading them back and modifying contents of the file.

 

“a+”    Searches file. If the file exits, loads t into memory and sets up a pointer, which points to the first character in it. If the file doesn’t exits, a new file is crated. Returns NULL, if unable to open file.

           

Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents.

 

 

 

Working with unformatted text file

Unformatted file I/O functions are

fgetc();

fputc();

fgets();

fputs() ;

 

High level, Text, Unformatted, Character I/O

fgetc() and fputc() are character I/O functions. As a practical use of these character I/O functions we can copy the contents of one file into another.

 

String (line) I/O in Files

High level, Text, Unformatted, string I/O

Reading or writing strings of characters from and to files is easy as reading and writing individual characters.

fputs() and fgets() are line I/O function in C.

 

The function fgets() takes three arguments. The first is the address where the string is stored, and the second is the maximum length of the string. The third argument is the pointer to the structure File. When all the lines from the file have been read, we attempt to read one more line, in which case fgets() returns a NULL.

 

 

Formatted Disk I/O Functions

For formatted reading and writing of characters, strings, integers, float, there exist two functions, fscanf() and fprintf(). Here is a sample program which illustrates the use of these functions

 

Example:Writing to file using formatted Disk I/O

#include<stdio.h>

#include<process.h>

void main()

{

            FILE *fp;

            char another ='Y';

            char name[40];

            int age;

            float bs;

            fp=fopen("EMPLOYEE.DAT","w");

           

while(another=='Y' || another=='y')

{

            printf("\nEnter name, age and basic salary\n");

            scanf("%s %d %f",name,&age,&bs);

            fprintf(fp,"%s %d %f\n",name,age,bs);

            printf("Another employee (Y/N)");

            fflush(stdin);

            another=getchar();

}

fclose(fp);

}

 

The key to this program is the function fprintf(), which writes the values of three variables to the file. This function is similar to printf(), except that a FILE pointer is included as the first argument. The function fflush()  is  designed to remove or ‘flush out’ any data remaining in the buffer. The argument to fflush() must be the buffer which we want to flush out. Here we use ‘stdin’, which means buffer related with standard input device the keyboard. After supplying data for one employee, we would hit the enter key and hence scanf() assigns name, age and salary to appropriate variables and keeps the enter key unread in the keyboard buffer. So it’s time to supply Y or N for the question “Another employee (Y/N)” getch() will read the enter key from the buffer thinking that user has entered the enter key. To avoid this problem we use the function fflush().

 

Following program will read back the names, ages and basic salaries of different employees which we stored through the earlier program into the file “EMPLOYEE.DAT”.

 

 

 

Example: Reading from File using Formatted I/O

#include <stdio.h>

#include<process.h>

void main()

{

            FILE *fp;

            char name[40];

            int age;

            float bs;

            fp=fopen("EMPLOYEE.DAT","r");

 

while(fscanf(fp,"%s %d %f\n",name, &age, &bs)!=EOF)

            printf("%s %d %.2f\n",name,age,bs);

            fclose(fp);

}

 

This program uses the fscanf() function to read the data from the disk. This function is similar to scanf(), except that, as with fprintf(), a pointer to FILE is included at the first argument.

 

Binary file

fread() and fwrite() functions are used for reading/writing records with binary file. The following program write records to a binary file.

 

Example: Writing to file using fwrite()

#include<stdio.h>

#include<process.h>

struct emp

{

char name[40];

int age;

float bs;

            };

void main()

{

FILE *fp;

char another='Y';

struct emp e;

fp=fopen("EMP.DAT","wb");

while(another=='Y' || another=='y')

            {

            printf("\nEnter name,age and basic sal.\n");

            scanf("%s %d %f", e.name,&e.age,&e.bs);

            fwrite(&e,sizeof(e),1,fp);

            printf("\n add another record(Y/N)");

            fflush(stdin);

            another=getchar();

            }

fclose(fp);

}

 

The information obtained about the employee from the keyboard is placed in the structure variable e. Then, the following statement writes the structure to the file.

            fwrite(&e,sizeof(e),1,fp);

Here, the first argument is the address of the structure to be written to the disk. The second argument is the size of the structure in bytes. Instead of counting the bytes occupied by the structure ourselves, we let the program do it for us by using sizeof() operator. sizeof() operator gives the size of the variable in bytes.

The third argument is the number of such structures that we want to write at one time. In this case, we want to write only one structure at a time.

The last argument is the pointer to the file we  want to write to.

Here is another sample that will read records from binary file and display them on monitor.

 

Example: Reading from file using fread()

#include<stdio.h>

#include<process.h>

void main()

{

            FILE *fp;

            struct emp

            {

                        char name[40];

                        int age;

                        float bs;

            };

 

                        struct emp e;

                        fp=fopen("EMP.DAT","rb");

                        while(fread(&e,sizeof(e),1,fp)==1)

                        printf("\n%s %d %.2f", e.name,e.age,e.bs);

            fclose(fp);

}         

 

Here, the fread() function causes the data read from the disk to be placed in the structure variable e. The format of fread() is same as fwrite(). The function fread() returns the number of records read. If we have reached the end of file, since fread()cannot read anything, it returns a 0. By testing for this situation, we know when to stop reading.

 Full Width

Post a Comment

0 Comments