员工的详细信息,即员工ID和由他们完成的文件没有需要存储在文件" employee.txt"。现在,存储到文件中的文件总数需要要显示。 我的程序代码在编译和执行时打印输出,但最后也给出了垃圾字符。 这是我的代码:
#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;
}
预期输出为: 输入:
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
输出:
The number of files done by all employees : 9
但是,我的输出显示:
The number of files done by all employees : 90/~
请帮我找到错误。我是C编程的新手
我还尝试在fprintf(stdout,"%d",total);
之后编写fprintf(fptr,"%d",total);
,从而避免在读取模式下再次打开文件,然后扫描并打印&#34;总计&#34;主要目标是简单地显示存储的文件总数。尽管如此,垃圾字符最后会显示出来。