File Handling in C programming language

Real time applications in C are created using the tecnique of file handling also know as file management. Files stores the group of related data. If the applocations are created without using the concept of files, the data might be lost when the system is shut down.

Basic file operations supported by C includes,
  • naming the files
  • opening the files
  • reading data from the files
  • writing data to the files
  • closing the files
C library comes with important built-in functions for handling the files. 

Function Name Function Description
fopen() Opens the file if exists or creates the new file.
fclose() Closes the file opened by fopen() function
getc() Used to read a single character at a time from the file
putc() Prints the single character at a time in the opened file
fscanf() A collection of data is read from a file
fprintf() Prints the collection of data in the opened file
getw() Used to read an integer from a file
putw() Writes the integer in a file
fseek() Used to set the position of cursor to the required point in the file
ftell() Gives the cursor position in the file from the start in terms of bytes
rewind() Used to set the file cursor to beginning of the file

Lets learn file handling with the examples.

Defining and Opening the files:


FILE *fp;
fp = fopen( "File name", "Mode");

FILE is defined in the C library and it is used for defining the file pointer.
fopen() function requires two inputs, one is the file name and the other on is mode.

There are 3 types of modes namely
Read - denoted by r
Write - denoted by w
Append - denoted by a

As the name specifies modes are self explanatory, r for reading the file, w for writing into the file and a for appending the data to the existing file or creates the new file and starts appending data to it.

Closing the files:



Closing the files requires only one input that is the file pointer pointing to the file. As file pointers are unique for files, closing the file doesn't require the file name or the mode with which the file is accessed.

Reading and writing to the files:


getc(file pointer);
putc(variable, file pointer);

getc is used for reading the content from the file character by character at a time. It will read the character pointed by the file pointer in the file till it reaches the EOF.

putc is used for writing the character from the content of variable into the file pointed by the file pointer.