File Handling in C

File Handling


File handling is a concept by which we can access and create any file in our local system.We know that a file is allocation of data or set of characters.Basically there are two type of file is used in C language such as Sequential and Random access file.Working with sequential files are easy compare to random file.In sequential file all the data are stored and retrieve in sequential manner But in random file data are stored and retrieve in random manner.

C language provide standard Input and Output library which contain many features such as character I/O, String I/O and Stream I/O.These features are differ from compiler to compiler.

Let we discuss these features one by one:


Character I/O


  1. getchar() :This function is used to read alphanumeric characters from user by any standard I/O device such as keyboard.
  2. putchar() :This function is used to display alphanumeric characters on the standard output device such as screen.
  3. getch() :This function does not accept any parameter but it return single character from keyboard.This function is used to stop accessing the keyboard as soon as any key is pressed.We can say that the running screen is hold until we press any key.
  4. putch() :This function is used to display alphanumeric characters on the standard output device such as screen.

If we want to use above functions than we must include <stdio.h> header file in our progream.

Example:

Copy Code
#include<stdio.h>
#include<conio.h>

int main()
{
    int ch;
    printf("Enter a character\n");
    ch=getchar();
    printf("Display character\n");
    putchar(ch);
    printf("\n");
   
    printf("Enter a character\n");
    ch=getch();
    printf("\n");
    printf("Display character\n");
    putch(ch); //Not run in some compiler
}

String I/O


  1. gets() :Reads a string from the keyboard.
  2. puts() :Write a string to the screen
  3. getc(stdin) :Read a single character from a stream (input stream such as stdin).
  4. putc(character,stdout) :Write a character character from a stream (output stream such as stdout).It has two parameters such as character and stdout

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char name[20];
        char ch='a';
        printf("Enter the name using gets():\n");
        gets(name);
        printf("Display name using puts():\n");
        puts(name);
       
        printf("Enter the name using getc():\n");
        getc(stdin);
        printf("Display the name using putc():\n");
        putc(ch,stdout);
    }
  5. sscanf() :This function is same as scanf function.But the difference is that it read the data form memory instead of keyboard.

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char str[]="amit singh;bhopal;20";
        char name[20];
        char city[10];
        unsigned int age;
        sscanf(str,"%[a-zA-Z ];%[a-zA-Z ];%d",name,city,&age);
        //[a-zA-Z ]-> means read a to z & A to Z & a space only
        // OR
        sscanf(str,"%[^;];%[^;];%d",name,city,&age);
        // [^;] means read all character except ;(semicolon) read as not semicolon
        printf("%s age is %d lived in %s",name,age,city);
    }

  6. sprintf() :This function is same as the printf function.But the difference is that it write any thing in memory in the place of screen.In this function one parameter must be a character array.

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char str[100];//="amit singh;bhopal;20";
        char name[20]="Shailendra";
        char city[10]="Bhopal";
        unsigned int age=40;
       
        sprintf(str,"%s age is %d lived in %s",name,age,city);
        // we store name city & age in variable str in formatted way
        printf("%s",str);
    }

Opening and Closing of Files

For opening and closing of any files we use following functions:

  • fopen()
  • fclose()

fopen()

fopen function is used to open file from the disk.This function have two parameters first is "file name" and second is "mode".

Syntax:

fptr=fopen(filename,mode);

fptr is a FILE pointer or pointer to a FILE type.
filename is a character string type.
mode means for what porpose we open a file such as for reading purpose,for writting purpose,for appending purpose.There abbreviation are given below.
  • "w" :This is a writting mode.In this mode open a file for writting purpose if exist and if not exist than create it.
  • "r" :This is a reading mode.In this mode open a existing file for reading content of file.If not exist NULL return to FILE pointer.
  • "a" :This a appending mode.In this mode open a existing file for appending the content of file.
  • "r+" :This mode is used to open an existing file for updating a existing file.
  • "w+" :This mode is used to create a new file for reading and writting.
  • "a+" :This mode is used for appending the content of file.If file does not exist then create it.

fclose()

fclose function is used to close the file that is used by program.Here close means remove the link form FILE pointer to the file name.

Syntax:

fclose(fptr); // fptr is a FILE pointer

Formatted Input and Output

  1. fprintf() :The stdio.h library provide fprintf() function for formatting Input/Output.Like printf() function fprintf also print the content but instead of printing in screen fprintf will write content into a given file.

    Syntax:

    fprintf(fptr,"control string",list)
    wherefptr is a file pointer.

  2. fscanf() :The stdio.h library provide fprintf() function for formatting Input/Output.Like scanf() function fscanf also read the content but instead of reading from keyboard fscanf will read content from a given file.

    Syntax:

    fprintf(fptr,"control string",&list)
    wherefptr is a file pointer.

  3. fgets() :The fgets function is used to read a set of characters as a string from a given file and copy the string to a given memory location generally in an array.This function will read the full line from a given file.

    Syntax:

    fgets(str,n,fptr)
    wherefptr is a file pointer.n is a maximum number of character in a string str.str is a array of string.

  4. fputs() :This function is used to write a string to a given file.

    Syntax:

    fputs(str,fptr)
    wherefptr is a file pointer.str is a array of string.

Example 1: Write a program to create a text file and store student record such as (Student Name, Student Rollno, Student Course, Student Branch, Student Rollno, Subjetct,Marks)

Copy Code
#include<conio.h>
#include<stdio.h>
void main()
{
    FILE *fptr;
    char name[30];
    char course[30];
    char branch[30];
    char subject[30];
    int marks,rollno;  
       
    fptr=fopen("D:\\student_rec.txt","a"); //We can write "a"-Append OR "w"-Write

    if(fptr==NULL)
    {
        printf("File does not exist\n");
        return;
    }

    printf("Enter name:\n");
    gets(name);
    fprintf(fptr,"Name    =%s\n",name);

    printf("Enter branch:\n");
    gets(branch);
    fprintf(fptr,"Branch   =%s\n",branch);

    printf("Enter course:\n");
    gets(course);
    fprintf(fptr,"Course   =%s\n",course);
   
    printf("Enter subject:\n");
    gets(subject);
    fprintf(fptr,"Subject   =%s\n",subject);  

    printf("Enter rollno:\n");
    scanf("%d",&rollno);
    fprintf(fptr,"Rollno     =%d\n",rollno);
   
    printf("Enter marks:\n");
    scanf("%d",&marks);
    fprintf(fptr,"Marks   =%d\n",marks);

    fclose(fptr);
    getch();
}

Output:



Example 2: Write a program to write text of 5 lines in file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","w");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Enter text :\n");
        // Write 5 lines in text file
        for(i=1;i<=5;i++)
        {
            gets(str);
            fputs(str,fptr);
            fputs("\n",fptr);
        }
   
    }
    fclose(fptr);
}

Output:

Example 3: Write a program to read text of 5 lines from file in screen.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","r");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Data in the file is :\n");
        // Read 5 line of text from file
        for(i=1;i<=5;i++)
        {
            fgets(str,100,fptr);            
            puts(str);
        }    
    }
    fclose(fptr);
}


Output:

Example 4: Write a program to append text of 5 lines in existing file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","a");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Enter text :\n");
        // Write 5 lines in text file
        for(i=1;i<=5;i++)
        {
            gets(str);
            fputs(str,fptr);
            fputs("\n",fptr);
        }
   
    }
    fclose(fptr);
}

Output:

Example 5: Write a program to append text of 10 lines in existing file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","r");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Data in the file is :\n");
        // Read 10 line of text from file
        for(i=1;i<=10;i++)
        {
            fgets(str,100,fptr);            
            puts(str);
        }    
    }
    fclose(fptr);
}



Read about more functions in hile handling such as:

  • getw()
  • putw()
  • fread()
  • fwrite()
  • feof()
  • ferror()
  • fflush()
  • freopen()
  • unlink()
  • open()
  • creat()
  • read()
  • write()
  • close()
  • lseek()
  • fseek()
  • ftell()
  • rewind()

No comments:

Post a Comment