Advertisment

File handling in C

author-image
CIOL Bureau
Updated On
New Update

Before starting with files in C, let’s try to integrate all that we’ve

learnt about pointers, structures etc. in the previous tutorials in a simple

program to update an inventory. This should be of help in getting an overall

picture.

Advertisment

The price and quantity of items stocked in a store change every day. To keep

track of this, an inventory must be maintained. This program reads the

incremental values of price and quantity and computes the total value of items

in stock.



 /* Program to update an
inventory */




 struct stores


 {


   char name<20>;


   float price;


   int qty;


 };





 main()


 {


   void update();


   float total(), value, pincr;


   int qincr;


   struct stores item, *ptr;


   ptr=&item /* Pointer ptr
points to structure item */






   /* Input values */


   printf("\nEnter the name,
price and quantity of item :");



   scanf("%s %f %d",ptr->name,&ptr->price,&ptr->qty);


   printf("\nInput increment
values for price and quantity:");



   scanf("%f
%d",&pincr,&qincr);






   /* Updating values by calling function update */


   update(ptr,pincr,qincr);


   printf("\nUpdated values of
item :\n");



   printf("Name :%s\n Price
:%f\n Quantity :%d\n",ptr->price, ptr->qty);






   /* Obtain the total value of item by calling function total
*/




   value=total(ptr);


   printf("\nTotal = %f",value);


 }



























 void update(p,x,y)



 struct stores *p;


 float x;


 int y;


 {


   p->price+ = x;


   p->qty+ = y;


 }





 float total(pt)


 struct stores *pt;


 {


   return(pt->price *
pt->qty);



 }











Continued...

Managing files



Now let’s move on to managing files in C. A file is another structured
datatype similar to an array. The characteristics of files are:

Advertisment
  1. File contents are stored in a permanent storage medium like disk.
  2. File data can be of different datatypes.
  3. Files can be arbitrary and of unlimited size whereas the size of an array

    is limited and has to be declared earlier.

So far, we’ve been using the scanf and printf functions to read and write

data. These are console oriented I/O functions and work fine as long as the data

is small. However, in cases that involve large volumes of data console oriented

I/O operations pose two problems:

  1. It becomes cumbersome and time consuming to handle large volumes of data

    through terminals.
  2. The entire data is lost when either the program is terminated or the

    computer is turned off.
Advertisment

Hence, it becomes necessary to have a more flexible approach where data can be

stored on the disk and read whenever necessary without destroying the data.

Hence the use of files to store data. A file is a place on the disk where a

group of related data is stored. In C, the

different I/O devices like keyboard and monitor are treated as files. The

keyboard acts as an input file and the monitor as an output file. C supports

several functions that have the ability to perform basic file operations like

opening, closing, reading, writing and naming a file.

Defining and opening a file



If we want to store data in a file in the secondary memory, we must specify
certain things about the file to the operating system. They include:

  1. Filename
  2. Data structure
  3. Purpose
Advertisment

Filename: can be made of two parts, a primary name and an optional

period with the extension. For example: trial.data, prog.c etc.



Data structure: of a file is defined as FILE in the library of
standard I/O function definitions. Therefore, all files should be declared as

type FILE before they are used. FILE is a defined datatype.



Purpose: when a file is opened we must specify the purpose i.e. what we
want to do with the file, for example whether we want to read data from the file

or write data to the file.



This is the format for declaring and opening a file:



FILE
*fp;



fp=fopen("filename","mode");


The first statement declares that variable fp is a pointer to the datatype FILE

and the second statement opens the file named filename and assigns an

identifier to the FILE type pointer fp. This pointer contains all

information about the file and is subsequently used as a communication link

between the system and the program. The ‘mode’ in the second statement

specifies the purpose of opening the file and can be one of the following:




r
    -   Open the file in the read mode only but

the file must already exist;




w
  -   Open the file in the write mode only, if the file

already exists the contents are overwritten. If it



       doesn’t
exist then a new file is opened for writing;




a
   -  Open the file in the append mode i.e. for adding data

at the end of file. If the file doesn’t exist



       a file
is created for writing. In this mode existing data is not overwritten.




r+ 
- Opens an existing file for reading and writing (the file must

exist).




w+
- Opens an empty file for reading and writing. If the file exists the

contents will be destroyed.




a+
  - The write operation results in appending of the data and existing

data will not be overwritten.

Note: both filename and mode are specified as strings and should be enclosed

in double quotation marks.



Consider the following statements:


 FILE *p1, *p2;


 p1=fopen("emp","r");


 p2=fopen("results","w");





Here, the file emp is opened for reading and results is opened for writing. If
the emp file doesn’t exist, an error will occur. In case the file results

already exists, it’s contents are deleted and the file is opened as a new

file.






Continued...Closing a file


A file must be closed as soon as all operations on it have been completed.
This ensures that all outstanding information associated with the file is

flushed out from the buffers and all links to the file are broken. It also

prevents accidental misuse of the file. In case there is a limitation on the

number of files that can be kept open simultaneously, closing any unwanted files

might help open the required files. Another instance where we would have to

close a file is when we want to reopen the same file in a different mode. Other

than these reasons, it's considered good programming practice to close

unwanted files. This is how we close a file:



 fclose(filepointer);








This closes the file associated with the FILE pointer ‘filepointer’.



Example:


 FILE *p1, *p2;


 p1=fopen("Input","w");


 p2=fopen("Output","r");


 ………………


 ………………


 fclose(p1);


 fclose(p2);


This program opens two files and closes them after all operations on them are
completed. Once a file is closed, its file pointer can be reused with another

file. All files are automatically closed whenever that program is terminated.








tech-news