Home » C Programming » File Handling in C Programming

File Handling in C Programming

A file represents a sequence of bytes and these file’s is used to store information. There are various different operations that we can be performed on a file are:

  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
  2. Opening an existing file (fopen)
  3. Reading from file (fscanf or fgetc)
  4. Writing to a file (filePointerrintf or filePointeruts)
  5. Moving to a specific location in a file (fseek, rewind)
  6. Closing a file (fclose)

Functions for file handling

There are various predefined functions available for handle file. Some of them mentioned below:

Function Description
fopen() Used for opens new or existing file
fprintf() Used for write data into the file
fscanf() Used for reads data from the file
fputc() Used for writes a single character into the file
fgetc() Used for  reads a single character from file
fclose() Used for closes the file
fseek() sets the file pointer to given position
fputw() Used for writes an integer to file
fgetw() Used for  reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file

Create or Open Files

We can create a new file or open an existing file by using fopen() function. To create a new file or open an existing file syntax is:

FILE   *fopen( const char * filename, const char * mode );

Here, filename is a string literal and use one of the following modes in the fopen() function if you are working with text file:-

File Mode Meaning of Mode
r opens a file in read mode. If the file does not exist, fopen() returns NULL.
w opens a file in write mode. If the file does not exist, fopen() returns NULL.
a opens a file in append mode ( Data is added to end of file). f the file does not exists, it will be created.
r+ opens a file in a both read and write mode. If the file does not exist, fopen() returns NULL.
w+ opens a file in both read and write mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+ opens a file in both read and write mode. If the file does not exists, it will be created.
Managed by MochaHost - Fast & Easy WordPress Hosting