File Handling / File Operations /data Files
File Handling / File Operations /data Files
Eg 3: Searching a record:
#include<stdio.h>
#include<conio.h>
struct stu
{
int id;
char name[20];
}s;
void main()
{
FILE *fp;
int idno, found=0;
clrscr();
fp=fopen("stu2pm","r");
if(fp==NULL)printf("File not found");
else
{
printf("Enter stuid ");
scanf("%d",&idno);
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(idno==s.id)
{
found=1;
puts("Id\tName");
puts("----------------------------");
printf("%d\t%s\n",s.id,s.name);
break;
}
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
if(found==0)printf("Student not available");
}
getch();
}
Eg 4: Editing a record [ Update ]
#include<stdio.h>
#include<conio.h>
struct stu
{
int id;
char name[20];
}s;
void main()
{
FILE *fp;
int idno, found=0;
clrscr();
fp=fopen("stu2pm","r+");
if(fp==NULL)printf("File not found");
else
{
printf("Enter stuid ");
scanf("%d",&idno);
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(idno==s.id)
{
found=1;
puts("Id\tName");
puts("----------------------------");
printf("%d\t%s\n",s.id,s.name);
printf("Enter new id, name ");
scanf("%d %s",&s.id,s.name);
fseek(fp,ftell(fp)-sizeof(s),0);
fwrite(&s,sizeof(s),1,fp);
printf("One row updated");
break;
}
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
if(found==0)printf("Student not available");
}
getch();
}
Eg 5 Deleting a record:
#include<stdio.h>
#include<conio.h>
struct stu
{
int id;
char name[20];
}s;
void main()
{
FILE *fp,*t;
int idno, found=0;
char ch;
clrscr();
fp=fopen("stu2pm","r");
if(fp==NULL)printf("File not found");
else
{
printf("Enter stuid ");
scanf("%d",&idno);
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(idno==s.id)
{
found=1;
puts("Id\tName");
puts("----------------------------");
printf("%d\t%s\n",s.id,s.name);
break;
}
fread(&s,sizeof(s),1,fp);
}
if(found==0)printf("Stu not available");
else
{
flushall();
printf("Ru sure to delete [y/n]");
scanf("%c",&ch);
if(ch=='n'||ch=='N')printf("Oeration
cancelled");
else
{
fp = fopen("stu2pm","r");
t = fopen("temp","w");
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(idno!=s.id)fwrite(&s,sizeof(s),1,t);
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
fclose(t);
remove("stu2pm");
rename("temp","stu2pm");
printf("One row deleted");
}
}
}
getch();
}