File Handling in "C"




File handling

Index

1.    Introduction
2.    File Operations
3.    Input Operations on File
4.    Output Operations on File
5.    Error handling
6.    Random access to Files



1.    Introduction
            In Computer, when we run programs, they use memory (RAM) to store the variables, which are temporary. Memory is volatile and its content will be in memory till the program is running, once the program get terminated, then values stored in parameter also erased. If we need data again then we need to use keyboard input. So this will be valid for small data, but for large data it’s not possible to enter data again and again when you require it and another way to get the values may be generate the values pragmatically. But both of the ways are very difficult to implement.
             So we need to store data on disk, which we can retrieve whenever we require. So here we are going to discuss how to store data on disk and perform various input and output operations.

Note: Data which we store on disk is always stored in form of binary data. Binary data which we store on disk may be varies from OS
                   

2.    File Operations
             There are different operations that we can carry out on a file.
These operations are general operations which we need to work on files
a.     Open a file
b.    Reading from file
c.     Writing to a file
d.    Append content to file
e.     Copy a file to another file
f.      Closing a file

     
  Prerequisites:
If we want to store data on secondary memory we must specify certain things like filename, purpose of file.
      Filename should be a valid filename supported by OS. File name generally have two parts which we knows. First part is known as valid filename and another part is known as extension. Extension part is optional part. Purpose refers to what we want to do with file, we need to read file or write to file or append to file.

a.     Open a file
Concept:        Before we read (or write) information from (to file) on a disk, we must open a file in particular mode. To open a file we use fopen() function. fopen() is a high level IO function. There are many high level IO function we use in file handling.

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)

        Types of Modes:
ð 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 an error. So one should handle such errors by error handling.
·       Example:

      
       FILE *fp;
fp= fopen(“service.txt”,”r”);
if(fp==NULL)
{
      printf(“File can’t found     ”);
exit();    
        }

   
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 *fp;
fp= fopen(“service.txt”,”w”);


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 *fp;
fp= fopen(“service.txt”,”a”);




b.     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.
8.    Example


#include<stdio.h>
#include<string.h>

void readFromFile(char* fileName);

void main()
{
          char fileName[20];
          printf("Enter File Name \t:");
          scanf("%s",fileName);
          fflush(stdin);                 //  Clear the buffer from memory
          readFromFile(fileName);  
         
}
void readFromFile(char* fileName)
{
       FILE *fp;            // File Pointer
             char c;
             fp= fopen(fileName,"r");    // Opening file in reading mode

             if(fp==NULL) 
             {
                 printf("File not found \n");
                       printf("Please check file Name\n");
                       exit();
             }

             printf("File Reading   :\n\n");
             printf("*************************************************\n\n");
       
             while((c=getc(fp))!=EOF)
             {
                 printf("%c",c);       // Display Characters on screen
             }
      
             printf("\n\n***********************************************\n");
             fclose(fp);            // Closing File Pointer
             printf("\n\n   %s File read successfully\n",fileName);
}



After executing this example, Result is displayed below



c.     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.

               putc(character, filePointer);

character - Character which we need to write to file
filePointer – pointing to file
4.    We can write to file using loops so that it will write character by character to file.
5.    Example: 



#include<stdio.h>
#include<string.h>

void writeToFile(char* fileName);

void main()
{
          char fileName[20];
          printf("Enter File Name \t:");
          scanf("%s",fileName);
          fflush(stdin);                 //  Clear the buffer from memory
          writeToFile(fileName);  
}


void writeToFile(char* fileName)
{
             FILE *fp;            // File Pointer
             char c;
             fp= fopen(fileName,"w");    // Opening file in writing mode
            
             printf("Enter the content , Enter ctrl+Z to exit   :\n\n");
             printf (“*****************************************\n\n”);
             while((c=getchar())!=EOF)
             {
                 putc(c,fp);        // Writing Characters in file using pointer
             }
           
             fclose(fp);            // Closing File Pointer
             printf (“\n\n*****************************************\n”);
             printf("%s File Written successfully\n",fileName);
}


After executing this example, Result is displayed below




Important Point –
1.    When we open file in write mode, automatic a buffer area will assigned to that pointer.
2.    The characters which we want to save on file, first save in that buffer area only, once we finishes our writing, then it will copy into that file.
3.    If the buffer gets full, then it will copy the content on disk or file and make space for new content
4.    At the end of file it puts EOF character to indicate end of file.
5.    Buffer plays a important role in writing text file or appending text.

a.     How to append text to a file
1.    To append text in a file we need to open the file in append mode.
We open the file in append mode by following way
          fp = fopen(fileName,”a”);
fp = File pointer
filename = name of file in which we need to append text

2.    To append the content we use same method which we did earlier in writing text file example
3.    We use putc function to append text file.

Note:  When we open the file in append mode, pointer point to end of file and so is append the content at end of file.


#include<stdio.h>
#include<string.h>

void appendToFile(char* fileName);

void main()
{
          char fileName[20];
          printf("Enter File Name \t:");
          scanf("%s",fileName);
          fflush(stdin);                 //  Clear the buffer from memory
         appendToFile(fileName);  
         
}
void appendToFile(char* fileName)
{
            FILE *fp;            // File Pointer
             char c;
             fp= fopen(fileName,"a");    // Opening file in appending mode
            
             printf("Enter content which you want to append   :\n\n");
             printf("******************************************\n\n");
         
             while((c=getchar())!=EOF)
             {
                 putc(c,fp);       // saving Characters in file
             }

             fclose(fp);            // Closing File Pointer
             printf("\n\n*************************************\n\n");
             printf("\n\n   %s  :  Content saved successfully\n",fileName);
}






a.     Copy a file to another file
1.    To copy a file to another file, we need two file pointers.
2.    File which we need to copy should be open in read mode (file A), as we don’t need to perform any write operation on that file. Another file we need to open in write mode(file B).
3.    We get character by character from file A and put that in file B.
4.    Example :


#include<stdio.h>
#include<string.h>

void copyFile(char* oldFileName, char* newFileName);

void main()
{
          char oldFileName[20],newFileName[20];
          printf("Enter the File Name which we need to copy \t:");
          scanf("%s",oldFileName);
          fflush(stdin);                 //  Clear the buffer from memory
         
          printf("Enter the new File Name \t:");
          scanf("%s",newFileName);
          fflush(stdin);                 //  Clear the buffer from memory

         copyFile(oldFileName,newFileName);  
         
}
void copyFile(char* oldFileName, char* newFileName)
{
            FILE *oldP,*newP;            // File Pointer
             char c;
             oldP= fopen(oldFileName,"r");    // Opening file in reading mode
             newP= fopen(newFileName,"w");

             if(oldP==NULL) 
             {
                 printf("File not found \n");
                       printf("Please check file Name\n");
                       exit();
             }

             
             while((c=getc(oldP))!=EOF)
             {
                 putc(c,newP);       // Display Characters on screen
             }
      
             fclose(oldP);            // Closing File Pointer
             fclose(newP);
             printf("\n\n    File copied successfully\n");
}

Comments

Post a Comment

Popular posts from this blog

Disable or enable proxy for Internet explorer or Chrome

chm viewer unable to show contents

3 prisoners and 5 hats puzzle