Header Ads

File Handling


Why files are needed?

We have learned how to store information in variables for use during the execution of a program, to store temporary or working, information. However, it is often necessary to store information permanently, so that it can be accessed again, even after the program has finished, the computer switched off etc.

When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, this information can be accessed using few commands.

A file is a collection of data that resides on the hard disk or on a removable floppy disk, or on a CD, and is completely independent from your C program. It may be a source file (which stores input for your program) or it may be a target file (to store output of your program).

C File operations - There are five Major Operation that can be performed on a file are:
  • Creation of n new file
  • Opening an existing file
  • Reading data from a file
  • Writing data in a file
  • Closing a file
Steps for processing a File
  • Declare a file pointer variable
  • Open a file using fopen() function
  • Process the file using suitable function
  • close the file using fclose() function 
Working with file

While working with file, you need to declare a pointer of type file. This declaration is needed for communication between file and program.

FILE *ptr;

fopen() and fclose() functions

Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
Syntax

       FILE *fp;
       fp= fopen(“filename”, "mode");

FILE = it's a data structure type.. Its defined in standard I/O function definitions
fp = this is a file pointer of type FILE data structure.
fopen= High level IO function
filename = valid filename which you want to open
mode = (read, write, append)

For Example:   fopen("E:\\cprogram\program.txt”, “w”);

/*-------------------------------------------------------*/
    E:\\cprogram\program.txt is the location to create file.
    "w" represents the mode for writing.
/* -------------------------------------------------------*/

Here, the program.txt file is opened for writing mode.

Types of Modes:

Types of mode

Reading mode

This mode is use when we need to perform read operation on file. In this mode we cannot perform any write operations.

For reading mode, in second argument of fopen function, we put "r". Second argument is not a character type.


it's a string. In reading mode if file exists,, then it will open file with contents safe otherwise it will give a error. So one should handle such errors by error handling.


Example:

file read
It will open the file "service.txt" in reading mode. First it will search for the file in directory, if file found then file pointer will point to starting of file. If that file not found then file pointer will point to NULL. So we can check file existence

Writing Mode:
  • This mode is use when we need to perform write operation on file.
  • For writing mode, we use "w" as second argument in fopen function.
  • In writing mode, if file does not exist, then it will create new file to that location. If file exists then it will erase all the contents, and open the file.
  • Example:
file write
It will open service.txt file in writing mode. We can save our data to file.

Appending mode:
  • This mode is also use when we need to perform write operation on file.
  • For appending mode, we use "a" as second argument in fopen function.
  • In Appending mode, if file does not exist, then it will create new file to that location. If file exists then it will open the file with all contents and points to end of file.
Example

file append
How to read from a text file?
  1. We need to open the file in Reading mode as we define earlier.
  2. Use library function to read content from file.
  3. Here we use getc function to read from file. This function reads character from current pointer location and returns character, which we can save in a character variable and display on screen.
  4. To read using this function we need a loop which will iterate through all characters and display on screen or perform any operation.
  5. We use while loop to iterate through the file, but before using any loop we need a condition to break the rule.
  6. In files, usually it puts a character at end of each file, we can check for this character and break the loop. This character has ASCII value of 26 and we can also define it as EOF. So we can check for this variable and break the rule. 
  7. EOF is defined in stdio.h file.

How to write in a text file?

  1. To write to file we need to open the file in writing mode.
  2. We use library function to perform write operation on file
  3. We use putc function to write to file.
  4. putc(character, filePointer);
  5. character - Character which we need to write to file
  6. filePointer-pointing to file
  7. We can write to file using loops so that it will write character by character to file
Closing a File

The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose(). 

Syntax

fclose(ptr); //ptr is the file pointer associated with file to be closed.

C provides a number of functions that helps to perform basic file operations. Following are the functions

file function
Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on file. getc()and putc() are simplest functions used to read and write individual. characters to a file

Code

#include<stdio.h> 
#include<conio.h> 
void main() 
{ 
 FILE *fp; 
 char ch; 
 fp = fopen("one.txt", "w"); 
 printf("Enter data"); 
 while((ch = getchar()) != EOF) 
 { 
  putc(ch,fp); 
 } 
 fclose(fp); 
 fp = fopen("one.txt", "r"); 
 while((ch = getc()) != EOF) 
   printf("%c",ch); 
 fclose(fp);     
}
Reading and Writing from File using fprintf() and fscanf()

The Functions fprintf() and fscanf() functions.
Important is that the functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE 

Code

#include<stdio.h> 
#include<conio.h> 
struct emp 
{ 
 char name[10]; 
 int age; 
}; 
void main() 
{ 
 struct emp e; 
 FILE *p.*q; 
 p = fopen("one.txt", "a"); 
 q = fopen("one.txt", "r"); 
 printf("Enter Name and Age"); 
 scanf("%s %d", e.name, &e.age); 
 fprintf(p,"%s %d", e.name, e.age); 
 fclose(p); 
 do 
 { 
  fscanf(q,"%s %d", e.name, e.age); 
  printf("%s %d", e.name, e.age); 
 } 
 while( !feof(q) ); 
 getch(); 
}

In this program, we have create two FILE pointers and both are referring to the same file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console using standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.

The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.

No comments

Powered by Blogger.