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();
    }

Post a Comment

Previous Post Next Post