File Handling in C Programming | File I/O operations in C

Till now, In every Tutorial we used to display the output of every program on the console/terminal. But in the Programming Industry, we may have to build large programs, where the output generated may be very large and it cannot be displayed on the screen, and due to the volatile nature of memory, the data(generated by the program for an instance) lost to it may never be recovered, and in such cases we need to store the output in a file, that may be present on the local file system or on the cloud/online.

File is a collection of bytes, regardless of the type, either binary or text stored on the System. C Language provides us with several powerful functions and methods to perform several operations on files like search, create, read, write, delete etc. Some terms might consider confusing to you, but don't worry we would be learning about each of them in detail.

Why we need Files

  • Files are needed to store the enormous amount of Data generated by a program, because it would be a very bulky task to obtain the Data again and again, by running the program, as when the program is terminated, the data is lost, and since it is volatile, it cannot be recovered.
  • For the ease in transportation of Data from one system to another.
  • Storing data on files helps in reducing the time, we waste in inputting the data.

Types of Files

In every System files are of 2 types, mentioned below:
  1. Text(ASCII) Files  :  These are the simple text files having extension .txt ,which can be created by any text-editor like notepad etc. Its contents are displayed in form of simple plain text. These files have the least security, but editing them or maintaining them is a very easy task.
  2. Binary Files : These are the files having extension .bin ,they store data in the form 0's and 1's, i.e in Binary Format, They are more secure than Text files as the data stored on them is not easily readable.

Basics of File Operations

In File-Handling we perform the below mentioned basic operations on the File:
  • Creating a new file
  • Opening an existing file
  • Reading from that file
  • Writing to that file
  • Closing the file
We can read and write from/to the files using the basic input output functions in C. The C Input/Output System provides a very consistent interface or a level of abstraction to the programmer to interact with the File system. This interface is known as Stream. There are 2 basic Streams: Input stream and the Output stream. These are used to read and write on the file.
The most common thread that unites the C I/O System is the File pointer. It is a pointer to the structure of type FILE. It points to the information that defines everything about the file, including its status and location. In C, all the file-handling functions and macros are defined in the stdio.h header file.
Some of the most common useful File-Handling functions in C are:

Introduction to File Modes

In most programming Languages, for every file operation, there exists a specific file mode, these help us to create, read, write, append or modify files in C. 

Working with Files

Before performing operations on the File, we first need to create a file pointer of the type FILE as discussed earlier.
Example:  FILE *ptr;

Opening/Creating a file 

To open  a file fopen() function is used with the required mode mostly 'r' or 'w'.

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

Example : FILE *fopen( "file1.txt" , "r");  //opening in read mode

* fopen() receives 2 arguments, that are the name of the file, which is a string and the mode in which we want to open the file. We can also pass the location of the file in place of the file name, to specify the location of the file. For example: FILE *fopen("C:\Users\Desktop\file.txt","r");
fopen() returns NULL if file is not opened successfully, Through this feature we can check whether file has opened or not. Using the following code:
if ( fp == NULL )
    {
        printf( "Could not open file test.c" ) ;
        return 1;
    }
Where fp is the file pointer

Important Points about some File Modes:

  • The 'r' mode as we know opens the file for reading, but if it is unable to open the file, then it returns NULL.
  • 'w' mode firstly searches the file that is to be open, and if it is found then it overwrites its contents. But if the file is not found, then it automatically creates a new file. And it also returns NULL if it is unable to open the file.
  • Most functions return NULL, in case they cannot open the file due to some reason.
  • 'a' mode when used it loads the file in the memory for adding data to it, unlike 'w' it does not overwrite the previous contents of the file. 

Reading from a file

It is performed using functions fscanf() or fgets(). They are very much similar to the scanf() and gets() function, only one more argument, i.e the File pointer is passed alongwith.

Syntax: 
int fscanf(FILE *stream, specifiers, variables);
char *fgets(char *str, int n, FILE *pointer);
* Here str is the pointer pointing to the place where the string read is stored, n is the max number of characters to be read.

Example:
fscanf(filePointer, "%s %s", str1, str2);
fgets (str, 60, fp);

Writing to a file

It is performed using fprintf() or fputs() functions, which work similar to printf() and puts(),but accepting one extra parameter(file pointer).

Syntax:
int fprintf(FILE *stream, format_specifiers,variables);
int fputs(const char *str, FILE *stream);

Examples:
fprintf(fp, "%s %s", "Programmer", "Studios");
fputs("Programmer Studios", fp);

Closing a file

It is done by using fclose() function, it also flushes all the buffers. It is necessory to close the file which we opened for performing operations.So as to free the occupied memory.

Syntax:
int fclose(FILE *stream);

Example:
fclose(file1);

Programs : 

Program 1 : 

#include<stdio.h>
int main() 
{
  FILE *fp;
  fp=fopen("abc.txt","r");
  
  if(fp)
    printf("File abc.txt opened successfully");
  else
    printf("Error in opening file");

  fclose(fp);
  return 0;
}

OUTPUT

File abc.txt opened successfully

Program 2 :

#include<stdio.h>
int main() 
{
 FILE *fp;
 fp=fopen("abc.dat","w");
 fputs("Hello, Welcome to the Code Quotient.", fp);
 fclose(fp);
 return 0;
}

OUTPUT

It writes "Hello, Welcome to the Code Quotient." to the file, without printing anything on the console.

Program 3 :

#include<stdio.h>
int main() 
{
  FILE *fp;
  char txt[100];
  fp=fopen("abc.dat","r");
  fgets(txt,50,fp); // Reads 50 bytes or till the end of file is encountered
  puts(txt);
  fclose(fp);
  return 0;
}

OUTPUT

It will read the First 50 lines of the file and print them on the screen console.

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post