The details of the employees, i.e,employee id and no of files done by them needs to be stored in a file "employee.txt".Now, the total count of files stored into the file needs to be displayed. My program code,when compiled and executed, prints the output but at the end gives junk characters too. Here is my code:
#include<stdio.h>
#include<stdlib.h>
struct emp
{
int emp_id;
int nof;
};
int main()
{
int no,total=0;
printf("Enter the number of employees\n");
scanf("%d",&no);
struct emp *e;
e=(struct emp*)malloc(no*sizeof(struct emp));
int i,j;
FILE *fptr;
fptr=fopen("employee.txt","wb");
for(i=0;i<no;i++)
{
fflush(stdin);
printf("For employee %d\n",i+1);
printf("Enter the employee id\n");
scanf("%d",&(e+i)->emp_id);
printf("Enter the number of files done\n");
scanf("%d",&(e+i)->nof);
}
fwrite(&e,sizeof(e),1,fptr);
for(i=0;i<no;i++)
{
total=total+(e+i)->nof;
}
fprintf( fptr,"%d",total);
fclose(fptr);
printf("Total number of files done by all employees : ");
FILE *fr;
fr=fopen("employee.txt","rb");
for(j=0;!feof(fr);j++)
{
fread(&e,sizeof(e),1,fr);
fscanf(fr,"%d",&total);
}
fclose(fr);
printf("%d",total);
return 0;
}
The expected output is: Input:
Enter the number of employees
3
For employee 1
Enter the employee id
470
Enter the number of files done
5
For employee 2
Enter the employee id
471
Enter the number of files done
3
For employee 3
Enter the employee id
472
Enter the number of files done
1
Output:
The number of files done by all employees : 9
But, my output is showing:
The number of files done by all employees : 90/~
Please help me find the errors.I am new to C programming in files.
I also tried writing fprintf(stdout,"%d",total);
after fprintf(fptr,"%d",total);
thereby avoiding opening the file again in read mode and then scanning and printing "total" as the main objective is to simply display the total no of files stored. Still, the junk characters get displayed at the end.