this is just the snippet.
the inappropriate here means:
if the file contains values:
name age salary
abby 23 27000
ashi 22 12345
then the output i am getting is:
name age salary
abby 23 27000.000000
ashi,*, 4320 1236457584382635.000000
m posting my entire code:
Code:
#include<stdio.h>
#include<stdlib.h>
struct _emp
{
char name[40];
int age;
float salary;
};
struct _emp emp;
void add(void); //adds details to the file
void display(void); //display the details of the file
void init_file(void);//initializes the file
int menu_select(void);//displays the menu and ask for the users' choice
int main(void)
{
char choice;
init_file(); //initialize the file
for(;;)
{
system("cls");
choice= menu_select();
switch(choice)
{
case '1': add(); break;
case '2': display(); break;
case '3': exit(0);
default: printf("enter the correct choice\n"); getch(); break;
}
}
return 0;
}
/****************************INITIALIZE FILE**********************************/
void init_file(void)
{
FILE *fp;
fp= fopen("details.txt", "r");
if(fp==NULL)
{
fp= fopen("details.txt", "w");
if(fp==NULL)
{
printf("cannot open the file\n");
getch();
exit(0);
}
fprintf(fp, "Name\t\t\t\tAge\tSalary\n");
}
fclose(fp);
}
/*********************DISPLAYS MENU AND ASKS FOR CHOICE************************/
int menu_select(void)
{
system("cls");
char choice;
printf("\t\t\t\tMENU.\n");
printf("\t\t\t\t=====\n");
printf("\t\t1. Enter the details into the file\n");
printf("\t\t2. Display the details on the screen\n");
printf("\t\t3. Exit\n");
printf("Enter the choice: ");
choice= getche();
return(choice);
}
/********************************ADD DETAILS TO THE FILE**********************/
void add(void)
{
FILE *fp;
char ch= 'y';
fp= fopen("details.txt", "a");
if(fp==NULL)
{
printf("cannot open file");
getch();
exit(0);
}
while(ch=='y')
{
printf("\nEnter name: ");
scanf("%s", emp.name);
printf("\nEnter age: ");
scanf("%d", &emp.age);
printf("\nEnter salary: ");
scanf("%f", &emp.salary);
fprintf(fp, "%s\t\t\t\t%d\t%f\t\n", emp.name, emp.age, emp.salary);
printf("\nEnter your choice(y/n): ");
fflush(stdin);
ch= getche();
}
fclose(fp);
return;
}
/**************************DISPLAYS THE DETAILS*******************************/
void display(void)
{
FILE *fp;
fp= fopen("details.txt", "r");
if(fp==NULL)
{
printf("cannot open file");
getch();
exit(0);
}
rewind(fp);
printf("\n");
while(fread(&emp, sizeof(struct _emp), 1, fp)==1)
printf("%s\t\t\t%d\t%f", emp.name, emp.age, emp.salary);
getch();
fclose(fp);
return;
}