#include<stdio.h>
#include<conio.h>
struct student
{
int rlno;
char na[20];
}; //structure for student data
struct student stu; //global variable for structure
//Function to recieve value of structure
void getdata()
{
printf("\n Enter Roll Num ");
scanf("%d",&stu.rlno);
printf("\n Enter Name ");
scanf("%s",stu.na);
}
//function to display values of structure
void showdata()
{
// printf("\n Name is %s ",stu.na);
// printf("\n Roll Num is %d ",stu.rlno);
printf("\n%d\t\t%s\n",stu.rlno,stu.na);
}
void main()
{
int ch; // var for choice
int choice;
int rl;
FILE *fp, *fp1;//var to open a file
while(choice!=5)
{
clrscr();
printf("\n 1. Add data ");
printf("\n 2. List Records ");
printf("\n 3. Delete Record ");
printf("\n 4. Modify Record ");
printf("\n 5. Quit");
printf("\n Enter your choice ");
scanf("%d",&choice);
switch(choice)
{
case 1:
fp=fopen("stud.txt","a"); //openning a file
while(ch!=0)//loop
{
getdata();//getting data
fwrite(&stu,sizeof(stu),1,fp);//writing to a file
printf("\n Press 1 to add more, 0 to quit ");//prompt the user for cont...
scanf("%d",&ch);
}
fclose(fp);//closing a file
break;
case 2:
fp=fopen("stud.txt","r"); //reopening a file
printf("\n Roll Num\t\tName");
printf("\n======================================\n");
while(fread(&stu,sizeof(stu),1,fp)==1)//loop for reading data
{
showdata();//display a data
}
fclose(fp);//closing a file
getch();
break;
case 3:
fp=fopen("stud.txt","r");
fp1=fopen("temp.txt","a");
printf("\n Enter rollnum u wanna delete ");
scanf("%d",&rl);
while(fread(&stu,sizeof(stu),1,fp)==1)
{
if(stu.rlno==rl)
{
printf("\n Record found ");
showdata();
printf("\n Press any Key to cont...");
getch();
}
else
{
fwrite(&stu,sizeof(stu),1,fp1);
}
}
fclose(fp);
fclose(fp1);
remove("stud.txt");
rename("temp.txt","stud.txt");
break;
case 4:
fp=fopen("stud.txt","r");
fp1=fopen("temp.txt","a");
printf("\n Enter rollnum u wanna Modify ");
scanf("%d",&rl);
while(fread(&stu,sizeof(stu),1,fp)==1)
{
if(stu.rlno==rl)
{
printf("\n Record found ");
showdata();
printf("\n Press any Key to enter new Values");
getch();
getdata();
fwrite(&stu,sizeof(stu),1,fp1);
}
else
{
fwrite(&stu,sizeof(stu),1,fp1);
}
}
fclose(fp);
fclose(fp1);
remove("stud.txt");
rename("temp.txt","stud.txt");
break;
case 5:
printf("\n Thanks for using this software ");
getch();
break;
default:
printf("\n Invalid Option ");
getch();
}//switch
}//while
}
No comments:
Post a Comment