File handling in c


  • File is a set of records that can be accessed through the set of library functions.
  • A file represents a sequence of bytes, does not matter if it is a text file or binary file.
  • C programming language provides access on high level functions as well as low level call to handle file on your storage device.

Types of File

There are two tyoes of files.

  • Sequential File
  • Random Access File

Sequential File

  • In this tyoe datas are kept sequentially. If we want to read the last record of the file we need to read all the records before that record. It takes more time.

Random Access File

  • In this type data can be read and modified randomly. In this type if we want to read the last records of file, we can read it directly. It takes less time as compared to sequential file.

File Operations:-

There are different operations that can be carried out on a file. These are:

  • Creation of a new file
  • Opening an existing file
  • Reading from a file
  • Writing to a file
  • Moving to a specific location in a file (seeking)
  • Closing a file
  •  

    Function Description
    fopen() create a new file or open a existing file
    fclose() closes a file
    getc() reads a character from a file
    putc() writes a character to a file
    fscanf() reads a set of data from a file
    fprintf() writes a set of data to a file
    getw() reads a integer from a file
    putw() writes a integer to a file
    fseek() set the position to desire point
    ftell() gives current position in the file
    rewind() set the position to the begining point
    feof() Detects the end of file.
    ftell() Returns the current pointer position.
    rename() Changes the name of file.

 

Opening a File

  • A file has to be opened before beginning of read and write operations. Opening of file creates a link between to operating system and the file functions. Opening a file is performed using library function fopen( ).
  • The syntax for opening file in standard I/O is:

    FILE * ptr;
    ptr = fopen("file_name","mode")

     

    Function Description
    r opens a text file in reading mode
    w opens or create a text file in writing mode.
    a opens a text file in append mode
    r+ opens a text file in both reading and writing mode
    w+ opens a text file in both reading and writing mode
    a+ opens a text file in both reading and writing mode
    rb opens a binary file in reading mode
    wb opens or create a binary file in writing mode
    ab opens a binary file in append mode
    rb+ opens a binary file in both reading and writing mode
    wb+ opens a binary file in both reading and writing mode
    ab+ opens a binary file in both reading and writing mode

 

Closing a File

  • To close a file, use the fclose(). The prototype of this function is :
  • int fclose(FILE*fp); 

    The fclose() returns zero on success, or EOF if there is an error in closing the file.