ChewTab

Thursday, October 05

C File Processing


Often the data in our programs needs to be stored on a permanent basis.The data stored in the variables and arrays in our codes and programs is temporary. To store the data permanently we need FILES. Files are stored mainly on the disk. So let's begin our discussion about files.

What is a file?
A file is a collection of bytes stored on a secondary storage device, generally a disk. A byte consists of 8 bits.A bit is either off or on, i.e it can have only two states which are 1 and 0. These bytes can be interpreted as decimal digits, letters or special symbols.A file is durable i.e. it is available for the programs even after the current program which created the file terminates.

File Creation and Writing
Let us now create a simple file and write to it.The program given below creates a file "strings.txt" and writes to this file whatever the user enters on the prompt.

#include<stdio.h>
#include<conio.h>
void main()
{
 FILE *f1;
 int i;
 char str[81];
 clrscr();

 printf("enter a string");
 gets(str);

 f1=fopen("string.txt","w");

 for(i=0;str[i]!='�';i++)
 {
 fprintf(f1,"%c",str[i]);
 }
 fclose(f1);

 getch();
 }

Line 5 in the code above states that f1 is a pointer to a FILE structure.For opening a file we must declare a pointer of the type "FILE" which must correspond or point to the file that we need to open.The function fopen used in line 12 opens the file "strings.txt" in the write mode.the function fopen takes two arguments i.e. a file name and the mode in which it has to be opened.The "w" indicates that the file has been opened in the writing mode.A file can be opened in various modes such as read, write, append etc.A complete list of modes is given here.If a file doesn't exist the fopen creates the file when opened in writing mode.Line 16 writes data to the file. The function fprintf sends formatted output to a stream.It takes as an argument a file pointer to which the data is written.Here we are writing to the file pointed by the pointer f1. At the end of the program, we use the function fclose. The function fclose receives as an argument the file to be closed.

File Reading

//record for 2 students for more number of students replace 2 by whatever u want
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
char name[50];
int student_id,quiz[5],total[100];

}s[100];

void main()
{
FILE *fp;
int i,j,m,k,g[100],b=0;
float average[5];
clrscr();
fp=fopen("data4.txt","w");
fprintf(fp,"name\tid\tquiz1\tquiz2\tquiz3\tquiz4\ttotal\n");
fclose(fp);
fp=fopen("data4.txt","a");
for(i=0;i<2;i++)
{
s[i].total[i]=0;
printf("Enter name ");
scanf("%s",&s[i].name);
fprintf(fp,"%st",s[i].name);
printf("Enter student id ");
scanf("%d",&s[i].student_id);
fprintf(fp,"%d\t",s[i].student_id);
for(j=1;j<5;j++)
{
printf("quiz %d:",j);
scanf("%d",&s[i].quiz[j]);
fprintf(fp,"%d\t",s[i].quiz[j]);
s[i].total[i]=s[i].total[i]+s[i].quiz[j];
}
fprintf(fp,"%d\n",s[i].total[i]);

printf("\n");
}
for(i=1;i<5;i++)
{
average[i]=0;
for(j=0;j<2;j++)
{
average[i]=average[i]+s[j].quiz[i];
}
average[i]=average[i]/2;
fprintf(fp,"average of quiz%d %f\n",i,average[i]);
}
fprintf(fp,"The students with 70% above in quiz 1 are:\n");

for(j=1;j<5;j++)
{
fprintf(fp,"\nThe students with 70 %% above in quiz %d are:\n",j);
for(i=0;i<2;i++)
{
if(s[i].quiz[j]>=17.5)
{
b=i;
fprintf(fp,"%s with id %d",s[b].name,s[b].student_id);
fprintf(fp,"\n");
b++;
}
}
}
fclose(fp);
fp=fopen("data4.txt","r");
printf("s.no.tnametidtquiz1tquiz2tquiz3tquiz4ttotaln");
for(i=0;i<2;i++)
{
fscanf(fp,"%dt%s",&s[i].student_id,s[i].name);
printf("%dt%st%dt",i,s[i].name,s[i].student_id);
for(j=1;j<5;j++)
{
fscanf(fp,"%dt",&s[i].quiz[j]);
printf("%dt",s[i].quiz[j]);
}
fscanf(fp,"%d",&s[i].total[i]);
printf("%d",s[i].total[i]);
printf("\n");
}
for(k=1;k<5;k++)
{
fscanf(fp,"%d",&average[k]);
printf("\naverage of quiz%d is %f",k,average[k]);
}
printf("\nThe students with 70% above in quizzes are:\n");

for(j=1;j<5;j++)
{
printf("\nThe student with 70 %% above in quiz %d\n",j);
for(i=0;i<2;i++)
{
if(s[i].quiz[j]>=17.5)
{
b=i;
printf("%s with id %d",s[b].name,s[b].student_id);
printf("\n");
b++;
}
}
}
fclose(fp);
getch();
}


OUTPUT
s.no.    name    id    quiz1    quiz2    quiz3    quiz4    total
0          Andy    12    22        12         11         9           66  
1          Rob      25    19        18         21         20         96
average of quiz1 is 18.5
average of quiz2 is 15
average of quiz3 is 16
average of quiz4 is 14.5

The students with 70% above in quizzes are:
The student with 70% above in quiz 1 Andy with id 12
The student with 70% above in quiz 1 Rob with id 25
The student with 70% above in quiz 2 Rob with id 25
The student with 70% above in quiz 3 Rob with id 25
The student with 70% above in quiz 4 Rob with id 25
#include <stdio.h>
#include <conio.h>
#include "valid.c"struct purch_detail
{
  char item_desc[20];
  int unit_price;
  int qty;
};

  void display();
  void entryData();
  void readFile();
  void getName(char *str);
  void getWriteFileName(char *);
  void getReadFileName(char *);
  void getzeroInteger(char *_chr, int *_value);

  int count=0;
  int total_price=0;
  int total_amt=0;
  char option;
  char filename [14];
  FILE *fp;
  struct purch_detail *pd_ptr, *tmptr;

  void main()
  {
      clrscr();
      pd_ptr = (struct purch_detail *) malloc(sizeof(struct purch_detail) * 10);
      tmptr = pd_ptr;

    printf("nDo you want to create the data file type 'y' for yes and 'n' for no.");
    scanf("%c", &option);
    fflush(NULL);

      if( option == 'y' || option == 'Y')
      {    printf("\nYou can generate bill of maximum 10 item.n");
       getWriteFileName(filename);
       display();
      }
      elseif( option == 'n' || option == 'N')
       {   getReadFileName(filename);
       readFile();
       }


      getch();
  }

  void entryData()
  {
     while(1)
     {
      printf("\nEnter item name : ");
      getName(tmptr->item_desc);

      getPosInteger("Enter unit price of the item : ", &tmptr->unit_price);
      getzeroInteger("Enter no of qty purchased : ", &tmptr->qty);

      if(tmptr->qty == 0)
        break;

      count ++;
      if (count >= 10)
         break;
     /* if ( count % 2 == 0)
       if ( (pd_ptr = (struct purch_detail *) realloc(pd_ptr, sizeof(struct purch_detail) * 2)) == NULL)
       {  printf("Realloc failed. No enough memory available.");
          break;
       }
       */

      tmptr++;
     }
  }

  void display()
  {
     tmptr = pd_ptr;

     fprintf(fp,"nItem                 Unit Price Quantity  Total Price ");
     fprintf(fp,"\n______________________________________________________");

     printf("\nItem                 Unit Price Quantity  Total Price ");
     printf("\n______________________________________________________");
     while(1)
     {
    total_price = tmptr->unit_price * tmptr->qty ;
    fprintf(fp, "\n%-20s      %4d    %4d     %5d", tmptr->item_desc, tmptr->unit_price, tmptr->qty, total_price);
    printf("\n%-20s      %4d    %4d     %5d", tmptr->item_desc, tmptr->unit_price, tmptr->qty, total_price);
    //printf("");
    total_amt += total_price;

    count--;
       if ( count <= 0)
        break;
      tmptr++;
     }

     fprintf(fp, "\n______________________________________________________");
     fprintf(fp, "\n\t\t\t    Total Amount : %5d", total_amt);
     printf("\n______________________________________________________");
     printf("\n\t\t\t    Total Amount : %5d", total_amt);
  }

   void getWriteFileName(char *fname)
   {
     printf("Enter Output File name maxium 14 character : ");
     scanf("%s", fname);

     if( ( fp = fopen(fname, "wt") ) == NULL  )
     {  fclose(fp);
    printf("\nInvalid file name entered.");
     }
     else
    entryData();
  }

   void getReadFileName(char *fname)
   {
     printf("Enter Input File name maxium 14 character : ");
     scanf("%s", fname);

     if( ( fp = fopen(fname, "r+t") ) == NULL  )
     {  fclose(fp);
    printf("\nInvalid file name entered.");
     }
   }

   void readFile()
   {
     char chr;
     while( feof(fp) == 0)
     {
     chr = getc(fp);
     printf("%c",chr);
     }
   }
    void getName(char *str)
    {
    int count1=0;
    char *getstr;
    char readch='�';
    int errorflag = 0;

       fflush(NULL);
       getstr = str;

       while(1)
       {
        scanf("%c", &readch);
        if( readch == 'n')
           break;

        *getstr = readch;

        count1++;
        getstr++;
        if( count1 >= 20 )
          break;
       }
       fflush(NULL);

       if(errorflag)
          getName(str);

       *getstr='�';
    }

 void getzeroInteger(char *_chr, int *_value)
 {
   float tempval =1;
   int _ival=0;

    printf("\n%s", _chr);
    _scaint = scanf("%f", &tempval);
    fflush(NULL);


   if ( _scaint != 0 )
   {
     _ival = tempval;

     if ( tempval < 0 )
     {
      printf("%s", "\nYou should enter value greater then or equal to zero. Enter the value again...");
      getzeroInteger(_chr, _value);
     }

     elseif ( _ival != tempval)
     {
      printf("%s", "\nError(decimal value). It will be truncated the digit after the percision. Enter integer number only.");
      getzeroInteger(_chr, _value);
     }
     elseif( ! ( (tempval >= -32768 ) && (tempval <= 32767 )  ) )
     {
      printf("%s", "\nError out of range entry. You should enter integer value in the range of -32768 to 327678 only.");
      getzeroInteger(_chr, _value);
     }
     else
     {
      *_value = (int) tempval;
     }

  }
  else
     {
    printf("\n%s","Error in entry. Enter integers only.");
    getzeroInteger(_chr, _value);
     }
 }

    /***************************   Input  *******************************


    Do you want to create the data file type 'y' for yes and 'n' for no.y


    You can generate bill of maximum 10 item.
    Enter Output File name maxium 14 character : output.txt

    Enter item name : soap

    Enter unit price of the item : 12

    Enter no of qty purchased : 3

    ***********************************************************************/
/********************************   OutPut ******************************

    Item                 Unit Price Quantity  Total Price
    ______________________________________________________
    soap                        15       3        45
    Coco Cola                   35       5       175
    Cadbury                     40       3       120
    ______________________________________________________
                    Total Amount :   340

    ************************************************************************/