Wednesday, 5 December 2012

File Programming in C: PART - 1

  Every Text Book covering Basics of C Programming will have a chapter titled "File Programming in C" towards the end of the text. What is meant by file programming ? The difference between ordinary programs and file programs is in the memory used to store the results. In case of ordinary programs the main memory is used to store the intermediate results and final results. Main memory is volatile and there for once the power is turned off the data stored is lost. This is the reason why ordinary C programs can't retain their results. To over come this problem file programming is used in C. Here the intermediate results are still kept in Main memory, but the final result is written back into a file kept in the hard disk. Since the files reside in the hard disk which is non volatile, it is possible to retain the results permanently. 

   A file pointer is used to hold the details of the file kept in the hard disk. A file pointer is a structure variable of a predefined special structure called FILE. The FILE structure is defined in the header file stdio.h. But to do file programming you don't need the details of the structure FILE. I have given it only for the consideration of advanced readers. The FILE structure is declared using typedef keyword in C. The code of FILE structure in Borland's Turbo C is given below.

                  typedef struct  
                         int             level;              /* fill/empty level of buffer */
                         unsigned        flags;         /* File status flags          */
                         char            fd;                 /* File descriptor            */
                         unsigned char   hold;       /* Ungetc char if no buffer   */
                         int             bsize;              /* Buffer size                */
                         unsigned char   *buffer;  /* Data transfer buffer       */
                         unsigned char   *curp;     /* Current active pointer     */
                         unsigned        istemp;      /* Temporary file indicator   */
                         short           token;           /* Used for validity checking */
                  }       FILE;  

  In Unix we can use System Calls like open, close etc. to manipulate files. Those topics I will cover in another Post.   

Click here to download C Programs illustrating File Programming using FILE Structure.

No comments:

Post a Comment