C File Operations and function

File pointers

It is not enough to just display the data on the screen. We need to save it because memory is volatile and its contents would be lost once program terminated, so if we need some data again there are two ways, one is retyped via keyboard to assign it to a particular variable, and the other is regenerate it via programmatically both options are tedious. At such times it becomes necessary to store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is usually a “file” on the disk.

Introduction to file

Until now we have been using the functions such as scanf,printf, getch, putch etc to read and write data on the variables and arrays for storing data inside the programs But this approach poses the following programs.

  • The data is lost when the program terminated or variable goes out of scope.
  • Difficulty to use a large volume of data.

We can overcome these problems by storing data on secondary devices such as Hard Disk. The data is stored on the devices using the concept of “file”. A file is a collection of related records, a record is composed of several fields and field is a group of character. The most straightforward use of files is via a file pointer.

The type FILE, is not a basic type, instead, it is defined in the header file stdio.h , this file must be included in your program.

File Operation

  • Create a new file.
  • Open an existing file
  • Read from file
  • Write to a file
  • Moving a specific location in a file(Seeking)
  • Closing File

Opening a file

Mode Description
r read
w write, overwrite file if it exists
write, but append instead of overwriting
w +
read & write, do not destroy file if it exists
a + read & write, but append instead of overwriting
bappended to any of the above to force the file to be opened in binary mode rather than text mode.

Sequential file access is performed with the following library functions:

fopen()  – Create a new file
 fclose()  – Close file
 getc()    – Read character from file
 putc()    – Write a character to a file
 getw()   – Read Integer from file
 putw()   – Write Integer to a file
 fprintf()  – Write set of data values
 fscanf()  – read set of data values