Saturday, 31 March 2012

Program - File Handling


Program – 1 : Write character to file

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

void main()
{
          FILE *fp;
          char ch;

          clrscr();

          fp=fopen("temp.txt","w");

          if (fp==NULL)
            {
                   printf("\n Error");
                   exit(0);
            }

          // write character to file
          printf("\n\nEnter Characters : \n");
          while((ch=getchar())!=EOF)
            {
                   fputc(ch,fp);
            }

          printf("\n data written successfully in file");
          fclose(fp);
          getch();

}

Program – 2: Read character from file
#include<stdio.h>
#include<conio.h>

void main()
{
          FILE *fp;
          char ch;

          clrscr();

          fp=fopen("temp.txt","r");

          if (fp==NULL)
            {
                   printf("\n Error");
                   exit(0);
            }

          // write character to file
          printf("\n\nData in file : \n");
          while((ch=fgetc(fp))!=EOF)
            {
                   putch(ch);
            }

          fclose(fp);
          getch();

}

Program – 3 : Copy the content of one file to another  file

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

void main()
{

          FILE *fp1,*fp2;
          char ch;

          clrscr();

          fp1=fopen("temp.txt","r");
          fp2=fopen("temp1.txt","w");

          if(fp1==NULL)
           {
              printf("\n File can not open ");
              getch();
              exit(0);
           }

         while((ch=fgetc(fp1))!=EOF)
            {
                   fputc(ch,fp2);
                   putch(ch);
            }


          printf("\n copied successfully ");
          fclose(fp1);
          fclose(fp2);

          getch();
}






Program – 4 : write number in file calculate total

#include<stdio.h>
#include<conio.h>
void main()
{
          FILE *fp1;
          int i,num,total=0,n;

          clrscr();

          fp1=fopen("n1.txt","w");
          printf("\n Enter How Many number U Want To Store : ");
          scanf("%d",&n);

          for(i=1;i<=n;i++)
          {
                   printf("\n Enter Number : ");
                   scanf("%d",&num);
                   putw(num,fp1);
          }
            fclose(fp1);

          fp1=fopen("n1.txt","r");

          printf("\n Content of file \n");

          while((num=getw(fp1))!=EOF)
          {
                   printf("\n %4d",num);
                   total=total+num;
          }

          printf("\n Total = %d ",total);
          fclose(fp1);
          getch();
}

Program – 5 : Write number in file , Find odd and even

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

void main()
{
          FILE *fp1,*fp2,*fp3;
          int i,num,n;

          clrscr();

          fp1=fopen("number.txt","w");
          printf("\n Enter How Many number U Want To Store : ");
          scanf("%d",&n);

          for(i=1;i<=n;i++)
          {
                   printf("\n Enter Number : ");
                   scanf("%d",&num);
                   putw(num,fp1);
          }
           fclose(fp1);
           fp1=fopen("number.txt","r");
          fp2=fopen("odd.txt","w");
          fp3=fopen("even.txt","w");

          printf("\n Content of NUMBER file \n");

          while((num=getw(fp1))!=EOF)
          {
                   printf("\t %4d",num);
                   if(num%2!=0)
                   {
                             putw(num,fp2);
                   }
                   else
                   {
                             putw(num,fp3);
                   }

          }

          fclose(fp2);
          fclose(fp3);

          // open file for reading purpose

          fp2=fopen("odd.txt","r");
          fp3=fopen("even.txt","r");

          printf("\n-----------------------");
          printf("\n Content of ODD file \n");

          while((num=getw(fp2))!=EOF)
           {
              printf("\t %4d",num);
           }

          printf("\n-----------------------");
          printf("\n Content of EVEN file \n");

          while((num=getw(fp3))!=EOF)
           {
              printf("\t %4d",num);
           }

          fclose(fp1);
          fclose(fp2);
          fclose(fp3);

          getch();
}

Program – 6 :  Write and read string from file

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


void main()
{
  FILE *fp1;
  char *s,ch;
  int c=0;
  clrscr();

  fp1=fopen("string1.txt","w");

  do
  {
    fflush(stdin);
    printf("\n Enter any string : ");
    gets(s);
    fputs(s,fp1);

    printf("\n Do you want to continue [y-n] : ");
    ch=getchar();
    if(ch=='y')
     {
          fputs("\n",fp1);
     }
  }while(ch=='y');

  fclose(fp1);

  if((fp1=fopen("string1.txt","r"))==NULL)
   {
      printf("\n Error " );
      exit(0);
   }

   while(!(feof(fp1)))
    {
       fgets(s,50,fp1);
       printf("\n %s",s);
       c++;
    }
   printf("\n Total number of lines : %d",c);
   getch();
  }




Program – 7 : Writing and reading mixed data (fprintf() , fscanf())

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

void main()
{
          FILE *fp;
          int icode,iqty,i;
          double iprice,iamt;
          char *iname;

          clrscr();

          fp=fopen("itemdata.txt","w");

          printf("\n ========Enter Data=======");
          for(i=0;i<2;i++)
          {
                   printf("\n------- Record - %d --------",i+1);
                   printf("\nEnter Item code : ");
                   scanf("%d",&icode);

                   fflush(stdin);
                   printf("\nEnter Item name : ");
                   gets(iname);
                   fflush(stdin);
                   printf("\nEnter Price     : ");
                   scanf("%lf",&iprice);
                   fflush(stdin);
                   printf("\nEnter Quantities : ");
                   scanf("%d",&iqty);
                   fflush(stdin);
                   iamt=iprice*iqty;

                   fprintf(fp,"%d %s %lf %d %lf",icode,iname,iprice,iqty,iamt);
                   fputs("\n",fp);

          }
          fclose(fp);

          fp=fopen("itemdata.txt","r");

          printf("\n----------------------------------------------------");
          printf("\n Records in File ");
          printf("\n----------------------------------------------------");
          printf("\n  Code\t  Name\t\t\tPrice\t Quantity\t Amount ");
          printf("\n----------------------------------------------------");
          for(i=0;i<2;i++)
           {
                   fscanf(fp,"%d %s %lf %d %lf",&icode,iname,&iprice,&iqty,&iamt);
                   printf("\n %d %s  %lf  %d  %lf",icode,iname,iprice,iqty,iamt);

           }
getch();
}


Program – 8 :  Writing and reading mixed data (fprintf() , fscanf()) as user desire

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

void main()
{
          FILE *fp;
          int icode,iqty,i=1;
          double iprice,iamt;
          char *iname,ans;

          clrscr();

          fp=fopen("itemdata1.txt","w");

          printf("\n ========Enter Data=======");
          do
          {
                   //iamt=0.0;
                   printf("\n------- Record - %d --------",i);
                   printf("\nEnter Item code : ");
                   scanf("%d",&icode);

                   fflush(stdin);
                   printf("\nEnter Item name : ");
                   gets(iname);

                   printf("\nEnter Price     : ");
                   scanf("%lf",&iprice);

                   printf("\nEnter Quantities : ");
                   scanf("%d",&iqty);

                   iamt=iprice*iqty;
                   fflush(stdin);
                   fprintf(fp,"%d %lf %d %lf %s",icode,iprice,iqty,iamt,iname);
                   printf("\n Do you want to continue [y-n] : ");
                   ans=getchar();
                   if(ans=='y' || ans=='Y')
                    {
                             fputs("\n",fp);
                             i++;
                    }
          }while(ans=='y' || ans=='Y');
          fclose(fp);

          fp=fopen("itemdata1.txt","r");

          printf("\n----------------------------------------------------");
          printf("\n Records in File ");
          printf("\n----------------------------------------------------");
          printf("\n  Code\t  Name\t\t\tPrice\t Quantity\t Amount ");
          printf("\n----------------------------------------------------");
          while(!feof(fp))
           {
                   fscanf(fp,"%d %lf %d %lf %s",&icode,&iprice,&iqty,&iamt,iname);
                   printf("\n %4d %-20s  %lf  %d  %lf",icode,iname,iprice,iqty,iamt);

           }
getch();
}



Program – 9 : Writing and reading records to file using structure

#include<stdio.h>
#include<conio.h>
struct emp
{
  char name[50];
  int age;
  float salary;
};

void main()
{

          FILE *fp;
          int i=1;
          char ans;
          struct emp e;
          clrscr();

          fp=fopen("employee.txt","w");
          if(fp==NULL)
           {
             printf("Error");
             getch();
             exit(0);
           }
          do
          {
                   printf("\n------- Record - %d --------",i);
                   fflush(stdin);

                   printf("\nEnter Employee name : ");
                   gets(e.name);
                    fflush(stdin);

                   printf("\nEnter Employee age  : ");
                   scanf("%d",&e.age);

                   printf("\nEnter salary        : ");
                   scanf("%f",&e.salary);

                   fflush(stdin);
                   fprintf(fp,"%s %d %f",e.name,e.age,e.salary);
                   printf("\n Do you want to continue [y-n] : ");
                   ans=getchar();
                   if(ans=='y' || ans=='Y')
                    {
                             fputs("\n",fp);
                             i++;
                    }
          }while(ans=='y' || ans=='Y');
          fclose(fp);

          fp=fopen("employee.txt","r");

          printf("\n----------------------------------------------------");
          printf("\n Records in File ");
          printf("\n----------------------------------------------------");
          printf("\n  Name\t\t\tAge\t Salary ");
          printf("\n----------------------------------------------------");
          while(fscanf(fp,"%s %d %f",e.name,&e.age,&e.salary)!=EOF)
           {
             printf("\n %-20s  %d  %.2f",e.name,e.age,e.salary);

           }
getch();
}

Program – 10:  Writing and reading block of bytes(fwrite(), fread())

#include<stdio.h>
#include<conio.h>
struct emp
{
  char name[50];
  int age;
  float salary;
};

void main()
{

          FILE *fp;
          int i=1;
          char ans;
       struct emp e;
          clrscr();

          fp=fopen("employee.txt","w");
          if(fp==NULL)
           {
             printf("Error");
             getch();
             exit(0);
           }
          do
          {
                   printf("\n------- Record - %d --------",i);
                   fflush(stdin);

                   printf("\nEnter Employee name : ");
                    gets(e.name);
                   fflush(stdin);

                   printf("\nEnter Employee age  : ");
                   scanf("%d",&e.age);

                   printf("\nEnter salary        : ");
                   scanf("%f",&e.salary);

                   fflush(stdin);
                   //fprintf(fp,"%s %d %f",e.name,e.age,e.salary);
                   fwrite(&e,sizeof(e),1,fp);
                   printf("\n Do you want to continue [y-n] : ");
                   ans=getchar();
                   if(ans=='y' || ans=='Y')
                    {
                         // fputs("\n",fp);
                             i++;
                    }
          }while(ans=='y' || ans=='Y');
          fclose(fp);

          fp=fopen("employee.txt","r");

          printf("\n----------------------------------------------------");
          printf("\n Records in File ");
          printf("\n----------------------------------------------------");
          printf("\n  Name\t\t\tAge\t Salary ");
          printf("\n----------------------------------------------------");
          while((fread(&e,sizeof(e),1,fp))==1)
           {
             printf("\n %-20s  %d  %.2f",e.name,e.age,e.salary);

           }
getch();
}







Program – 11 :  Writing and reading block of bytes(fwrite(), fread())  usng array

#include<stdio.h>
#include<conio.h>
struct emp
{
  char name[50];
  int age;
  int salary;
};

void main()
{

          FILE *fp;
          int i=1;
          char ans;
       struct emp e[10];
          clrscr();

          fp=fopen("employee1.txt","wb");
          if(fp==NULL)
           {
             printf("Error");
             getch();
             exit(0);
           }
       for(i=0;i<2;i++)
          {
                   printf("\n------- Record - %d --------",i+1);
                   fflush(stdin);

                   printf("\nEnter Employee name : ");
                   gets(e[i].name);
                   fflush(stdin);

                   printf("\nEnter Employee age  : ");
                   scanf("%d",&e[i].age);

                   printf("\nEnter salary        : ");
                   scanf("%d",&e[i].salary);

                   fflush(stdin);
                   //fprintf(fp,"%s %d %f",e.name,e.age,e.salary);
                   }
          fwrite(&e,sizeof(e),2,fp);

          fclose(fp);

          fp=fopen("employee1.txt","rb");

          printf("\n----------------------------------------------------");
          printf("\n Records in File ");
          printf("\n----------------------------------------------------");
          printf("\n  Name\t\t\tAge\t Salary ");
          printf("\n----------------------------------------------------");
          if((fread(&e,sizeof(e),2,fp))!=2)
           {
             printf("\n no records \n\n");
           }
          for(i=0;i<2;i++)
           {
             printf("\n %-20s  %d  %d",e[i].name,e[i].age,e[i].salary);

           }
getch();
}

Program – 12 :  Random access file

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

void main()
{
    FILE *fp;
    long n;
    char ch;
    clrscr();

    fp=fopen("content.txt","w+");
    printf("\n Write character content to the file foe exit press ctrl+Z: \n ");

    while((ch=getchar())!=EOF)
     {
           fputc(ch,fp);
     }

     printf("Content written in file");

     printf("\n no of characters entered in file : %ld",ftell(fp));
     rewind(fp);   // fseek(fp,0L,0)
     n=0L;

     while(feof(fp)==0)
       {
            fseek(fp,n,0);
            printf("\n %c at position %ld ",fgetc(fp),ftell(fp));
            n=n+1L;
       }
   // getch();

    fseek(fp,-1L,2);
    printf("\n %c",fgetc(fp));
     printf("\n -1L -> %ld",ftell(fp));
    fseek(fp,-2L,2);
    printf("\n %c",fgetc(fp));
    printf("\n -2L-> %ld",ftell(fp));

     fclose(fp);
     getch();
    }



Program – 13 :  Searching of record from data file

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

struct item
{
          int no,qty;
          float price;
          char iname[10];
};

void main()
 {
          FILE *fp;
          long size;
          int c=1,x;
          struct item i;
          char ans;

          clrscr();

          fp=fopen("data.txt","wb+");

          printf("\n ========Enter Data=======");
          do
          {
                   printf("\n------- Record - %d --------",c);
                   fflush(stdin);

                   printf("\nEnter item number  : ");
                   scanf("%d",&i.no);

                   fflush(stdin);
                   printf("\nEnter item name    : ");
                   gets(i.iname);
                   fflush(stdin);

                   printf("\nEnter price        : ");
                   scanf("%f",&i.price);

                   printf("\nEnter Quantity     : ");
                   scanf("%d",&i.qty);

                   fwrite(&i,sizeof(i),1,fp);
                   fflush(stdin);

                   printf("\n Do you want to continue [y-n] : ");
                   ans=getchar();

                   if(ans=='y' || ans=='Y')
                    {

                             c++;
                    }
          }while(ans=='y' || ans=='Y');

          rewind(fp);

          printf("\n Enter record number for searching : ");
          scanf("%d",&x);

          if(x<=c)
            {
                   x--;
                   fseek(fp,x*sizeof(i),0);
                   printf("\nPosition Of the pointer in file: %ld\n",ftell(fp));
                   fread(&i,sizeof(i),1,fp);
                   printf("\n\n %d %s  %f  %d \n",i.no,i.iname,i.price,i.qty);
            }
          else
           {
              printf("\n No record found ");
           }
          getch();
}

Program – 14 :  Display command line argument

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

void main(int argc,char *argv[])
 {
    int i;
    clrscr();

    printf("\n Total argument : %d",argc);


    for(i=0;i<argc;i++)
      printf("\n %s",argv[i]);
    getch();
 }






Program – 15 : Numeric argument and calculate its sum.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>

void main(int argc,char *argv[])
 {
    int i,no,s=0;
    float avg;

    clrscr();

    printf("\n Total argument : %d",argc);
    printf("\n file name = %s ",argv[0]);

    for(i=1;i<argc;i++)
     {
          // Convert string to number
          no=atoi(argv[i]);
          printf("\n no = %d ",no);
          s=s+no;
     }
    avg=s/argc;

     printf("\n Sum = %d",s);
    printf("\n average = %f",avg);
    getch();
 }

Program – 16 :  Write and read string from file using command prompt

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


void main(int argc,char *argv[])
{
  FILE *fp1;
  char *s,ch;
  int i;
  clrscr();

  if(argc>=1)
   {
     fp1=fopen(argv[1],"w");
   }
  else
   {
     printf("\n no command line argument ");
     getch();
     exit();
   }

  for(i=2;i<argc;i++)
  {
      fprintf(fp1,"%s",argv[i]);
      if(i<argc-1)
          fputs("\n",fp1);
  }

  fclose(fp1);

  if((fp1=fopen(argv[1],"r"))==NULL)
   {
      printf("\n Error " );
      getch();
      exit(0);
   }

   while(!(feof(fp1)))
    {
       fscanf(fp1,"%s",s);
       printf("\n%s",s);

    }

   getch();
  }

Program – 17 :  copy content of one file to another file File name should be given from command prompt

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


void main(int argc,char *argv[])
{
  FILE *fs,*ft;
  char ch,ans;
  int i;

  clrscr();

  if(argc!=3)
   {

   printf("\n Not enough paramenter ");
   getch();
   exit(0);
   }

// open source file in read mode

  fs=fopen(argv[1],"r");
  if(fs==NULL)
   {
      printf("\n source file not found : %s",argv[1]);
      getch();
      exit(0);
   }

// check whether the file names are same or not
if(strcmp(argv[1],argv[2])==0)
  {
     printf("\n Can not copy to itself ");
     getch();
     exit(0);
  }

// open target file in write mode

  ft=fopen(argv[2],"w");
  while((ch=fgetc(fs))!=EOF)
   {
     fputc(ch,ft);
   }

   printf("\n 1 file cpoied ");


   getch();
  }


Posted By : Ruchita Pandya


No comments:

Post a Comment