Thursday, June 28, 2012

File operation in ‘C’ - III



Example of Write, Read, modify and delete.

//Write, Read, modify and delete

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

struct emp
      {
           char name[30];
           int days,wages,sal;
      }emp;

  void add()
      {
           FILE *fptr;
           fptr=fopen("emp.txt","w");
           printf("\n\tEmployee Name:");
           fflush(stdin);
           gets(emp.name);
           fflush(stdin);
           printf("\n\tDays Worked : ");
           scanf("%d",&emp.days);
           printf("\n\tWages : ");
           scanf("%d",&emp.wages);
           emp.sal=emp.days*emp.wages;
           fwrite(&emp,sizeof(emp),1,fptr);
           fclose(fptr);
      }

  void disp()
      {
           FILE *fptr;
           fptr=fopen("emp.txt","r");
           printf("\n\n\t Employee\t\t\tDays\tWage\tSalary");
           printf("\n\t   Name");
           printf("\n\t======================================================");
           while(fread(&emp,sizeof(emp),1,fptr)==1)
              {
                   printf("\n\t %-30s\t %d\t %d\t %d",emp.name,emp.days, emp.wages, emp.sal);
              }
           printf("\n\t======================================================");
      }
  void modify()
      {
           char name[20];
           FILE *fptr,*fptr1;
           int flag=0;
           fptr=fopen("emp.txt","r");
           fptr1=fopen("temp.txt","w");
           printf("\n\tEnter Employee Name to Modify: ");
           fflush(stdin);
           gets(name);
           fflush(stdin);
           while(fread(&emp,sizeof(emp),1,fptr)==1)
              {
                   if(stricmp(emp.name,name)==0)
                        {
                            flag=1;
                            printf("\n\tEnter New Days & Wage:");
                            scanf("%d%d",&emp.days,&emp.wages);
                            emp.sal=emp.days*emp.wages;
                        }
                   fwrite(&emp,sizeof(emp),1,fptr1);
              }
           if(flag==1)
              {
                   printf("\n\tThe Profile is Modified");
              }
           else
              {
                   printf("\n\tRecord is Not Found!!");
              }

           fclose(fptr);
           fclose(fptr1);
           remove("emp.txt");
           rename("temp.txt","emp.txt");
      }
  void del()
      {
           char name[20];
           FILE *fptr,*fptr1;
           int flag=0;
           fptr=fopen("emp.txt","r");
           fptr1=fopen("temp.txt","w");
           printf("\n\tEnter Employee Name to Delete : ");
           fflush(stdin);
           gets(name);
           fflush(stdin);
           while(fread(&emp,sizeof(emp),1,fptr)==1)
              {
                   if(stricmp(emp.name,name)!=0)
                        {
                            fwrite(&emp,sizeof(emp),1,fptr1);
                        }
                   else
                        {
                            flag=1;
                        }
              }
           if(flag==1)
              {
                   printf("\n\tThe Profile is Deleted");
              }
           else
              {
                   printf("\n\tRecord is Not Found!!");
              }
           fclose(fptr);
           fclose(fptr1);
           remove("emp.txt");
           rename("temp.txt","emp.txt");
      }

  void main()
      {
           int c=0;
           clrscr();
           while(c<5)
              {
                   printf("\n\n\t1. Add");
                   printf("\n\t2. Display");
                   printf("\n\t3. Delete");
                   printf("\n\t4. Modify");
                   printf("\n\t5. Exit");
                   printf("\n\tYour Choice : ");
                   scanf("%d",&c);
                   switch(c)
                        {
                            case 1:add();break;
                            case 2:disp();break;
                            case 3:del();break;
                            case 4:modify();break;
                        }
              }
           getch();
      }

Thursday, June 21, 2012

File operation in ‘C’ - II


Here is another example of File Operation with fread() and fwrite().


#include <stdio.h>
#include <conio.h>
#include <dos.h>
  struct empl
      {
           char name[30];
           float sal;
           struct {int dd,mm,yy;}db,rd;
      }em,*emp;
  int c;
  int d1[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  int pr(int c)
      {
           FILE *fp;
           int y,m,d,y1;
           int count=0;
           struct date dts;
           getdate(&dts);
           fp=fopen("emp.txt","r");
           if(c==1)
               {
                    printf("\n-----------------------------------------------------------------------------");
                    printf("\n  Employee               Salary    Date of        Date of     Years Left");
                    printf("\n    Name                            Birth        Retirment   For Retirement");
                    printf("\n-----------------------------------------------------------------------------");
               }
           while(fread(&em,sizeof(em),1,fp)==1)
               {
                    if(c==0)
                             count++;
                    else
                         {
                             printf("\n  %-20s  %8.2f   %2d-%2d-%4d    %2d-%2d-%4d  ",em.name,em.sal,em.db.dd,em.db.mm,em.db.yy,em.rd.dd,em.rd.mm,em.rd.yy);
                             y=em.rd.yy-em.db.yy;
                             m=em.rd.mm-em.db.mm;
                             d=em.rd.dd-em.db.dd;
                             if(m<0)
                                  {
                                       y=y-1;
                                       m=12-m;
                                  }
                             if(d<0)
                                  {
                                       m=m-1;
                                       d=m[d1]-em.db.dd;
                                  }
                             y1=(em.rd.yy-em.db.yy)-(dts.da_year-em.db.yy);
                             printf("     %d",y1);
                    }
               }
           if(c==1)
               {
                    printf("\n-----------------------------------------------------------------------------");
               }
           return count;
      }

  void write()
      {
           FILE *fp;
//      c=pr(c);
           fp=fopen("emp.txt","a");
           fflush(stdin);
           printf("\n\t\tEnter Emplyee Name : ");
           gets(em.name);
           printf("\n\t\tEnter Emplyee Salary : ");
           scanf("%f",&em.sal);
           printf("\n\t\tEnter Emplyee Date of Birth (dd mm yyyy) : ");
           scanf("%d",&em.db.dd);
           scanf("%d",&em.db.mm);
           scanf("%d",&em.db.yy);
           printf("\n\t\tEnter Emplyee Date of Retirement (dd mm yyyy) : ");
           scanf("%d",&em.rd.dd);
           scanf("%d",&em.rd.mm);
           scanf("%d",&em.rd.yy);
           fwrite(&em,sizeof(em),1,fp);
           fclose(fp);
      }
  void sort()
      {
           FILE *fp;
           int i,j;
           struct empl emp1;
           c=pr(0);
           emp=(struct empl *)malloc(sizeof(c));
           fp=fopen("emp.txt","r");
           i=0;
           while(fread(&em,sizeof(em),1,fp)==1)
               {
                    emp[i]=em;
                    i++;
               }
           fclose(fp);
           for(i=0;i<c-1;i++)
               {
                    for(j=i+1;j<c;j++)
                         {
                             if(emp[i].sal>emp[j].sal)
                                  {
                                       emp1=emp[i];
                                       emp[i]=emp[j];
                                       emp[j]=emp1;
                                  }
                         }
               }
           fp=fopen("emp.txt","w");
           i=0;
           while(i<c)
               {
                    em=emp[i];
                    fwrite(&em,sizeof(em),1,fp);
                    i++;
               }
           fclose(fp);
      }
  void main()
      {
           int cn=0;
           clrscr();
           while(cn<4)
               {
                    printf("\n\n\n\n\t1. Write\n\t2. Print\n\t3. Sort\n\t4. Exit");
                    printf("\n\tEnter a Choice : ");
                    scanf("%d",&cn);
                    switch(cn)
                         {
                             case 1:write();break;
                             case 2:pr(1);break;
                             case 3:sort();printf("\nAfter Sort\n");pr(1);break;
                         }
               }
           getch();
      }

Thursday, June 14, 2012

File operation in ‘C’



File operation in any programming language is meant for saving the data, so it can be called as data file. C is still is a low-level language if we goes by the present standard. In C file operations mainly depends on streams of bytes, that are known as "input streams" or "output streams". C language does not support any Random files as some of previous languages like COBOL and BASIC. All required function for File Operations are mentioned in "stdio.h", it was written by Mike Lesk at Bell Labs in the early 1970s.

Main functions for File Operations -

FILE pointer from "stdio.h" must be use to perform File operations.

Example :
FILE *fp;

There are many input/output statement that mainly meant for file operations. If we opened a file then we should close.

fopen(), function used to open a file. We can open a file for reading or writing or for modifying purpose too.

"r"- Read-Only mode.
"w"-Write-only mode.
"a"-append mode.
"r+"-read+write mode.
"w+"-write+read mode.
"a+"-read+append mode.

fclose() - is for closing a file.

For reading, writing or searching a record we can using following functions
fgetc()
fgets()
fscanf()
fputc()
fprintf()
fputs()
fseek()
rewind()

Here is a few example on File Operation, where we will try to cover a few functions that exclusively related to the file operation.


//Writing and Reading character wise using putc() and getc()
#include <stdio.h>
#include <conio.h>
#include <string.h>

  void FileWrite()
      {
           char Filename[11],sentence[100];
           int i=0;
           FILE *fptr;
           fflush(stdin);
           printf("\n\tEnter Filename   : ");
           gets(Filename);
           fflush(stdin);
           printf("\n\tEnter a Sentence :  ");
           gets(sentence);
           fptr=fopen(Filename,"w");
           do
              {
                   putc(sentence[i++], fptr);
              }while(sentence[i]!='\0');
           fclose(fptr);
      }

  void FileRead()
      {
           char Filename[11],sentence[100];
           int i=0;
           FILE *fptr;
           fflush(stdin);
           printf("\n\tEnter Filename   : ");
           gets(Filename);
           if ((fptr = fopen(Filename, "r"))== NULL)
              {
                   printf("\n\n\tFile Doesnot Exists ");
                   getch();
                   return;
              }
           fptr=fopen(Filename,"r");
           while((sentence[i++]=getc(fptr))!=EOF);
           sentence[i]='\0';
           fclose(fptr);
           printf("\n\tSentence Extract from File is = %s ",sentence);
      }

  void main()
      {
           int c=0;
           clrscr();
           while(c<3)
              {
                   printf("\n\n\n\t1. Write\n\t2. Read\n\t3. Exit");
                   printf("\n\tenter your choice:");
                   scanf("%d",&c);
                   switch(c)
                        {
                            case 1:FileWrite();break;
                            case 2:FileRead();break;
                        }
              }
           getch();
      }




//Writing and Reading whole string using fputs() and fgets()
#include <stdio.h>
#include <conio.h>
#include <string.h>

  FILE *fp;
  int c;
  void FileCreate()
      {
           char wrd[50],ch='y';
           int L;
           fp=fopen("Word.txt","w");
           while(ch=='y' || ch=='Y')
              {
                   fflush(stdin);
                   printf("\n\tEnter a String : ");
                   gets(wrd);
                   fputs(wrd,fp);
                   fputs("\n",fp);
                   fflush(stdin);
                   printf("\n\tWant to continue y/n? ");
                   ch=getche();
              }
           fclose(fp);
      }
  void FileRead()
      {
           char wrd[50];
           if((fp=fopen("word.txt","r"))==NULL)
              {
                   printf("\n\n\tInvalid Filename");
                   getch();
                   return;
              }
           printf("\n\tStrings read from the file :");
           while(fgets(wrd,50,fp)!=NULL)
              {
                   printf("\n\t%s",wrd);
              }
           fclose(fp);
      }
  void main()
      {
           int c=0;
           clrscr();
           while(c<3)
              {
                   printf("\n\n\n\t1. Write\n\t2. Read\n\t3. Exit");
                   printf("\n\tenter your choice:");
                   scanf("%d",&c);
                   switch(c)
                        {
                            case 1:FileCreate();break;
                            case 2:FileRead();break;
                        }
              }
           getch();
      }


//Writing and Reading using fprintf() and fscanf()
#include <stdio.h>
#include <conio.h>
#include <string.h>

  void FileCreate()
      {
           char ch='y',name[20];
           int age,i;
           FILE *fp;
           fp=fopen("Details.txt","w");
           while(ch=='y' || ch=='Y')
              {
                   printf("\n\tEnter name : ");
                   scanf("%s",&name);
                   printf("\n\tEnter age : ");
                   scanf("%d",&age);
                   fprintf(fp,"%s %d",name,age);
                   printf("\n\tWant to continue (y/n)? ");
                   ch=getche();
                   printf("\n");
              }
           fclose(fp);
      }

  void FileRead()
      {
           char name[20];
           int age,i;
           FILE *fp;
           fp=fopen("Details.txt","r");
           while((fscanf(fp,"%s %d",&name,&age))!=EOF)
              {
                   printf("\n\n\tname : %s ",name);
                   printf("\n\tAge :  %d",age);
              }
           fclose(fp);
           getch();
      }

  void main()
      {
           int c=0;
           clrscr();
           while(c<3)
              {
                   printf("\n\n\n\t1. Write\n\t2. Read\n\t3. Exit");
                   printf("\n\tenter your choice:");
                   scanf("%d",&c);
                   switch(c)
                        {
                            case 1:FileCreate();break;
                            case 2:FileRead();break;
                        }
              }
           getch();
      }