我正在尝试将struct employee写入文件,但无论我输入case语句多少次,它都只会写入最近输入的一个。
case '1':
{
fptr=fopen("program.bin","wb");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
printf("\nA is: %d\n",a);
printf("\nPlease enter the employee's ID: ");
scanf("%s",&employee[a].ID);
fprintf(fptr,"Employees ID number: %s\r\n",employee[a].ID);
printf("\nPlease enter the employee's first name: ");
scanf("%s",&employee[a].firstname);
fprintf(fptr,"Employees first name: %s\r\n",employee[a].firstname);
printf("\nPlease enter the employee's Surname: ");
scanf("%s",&employee[a].surname);
fprintf(fptr,"Employees surname: %s\r\n",employee[a].surname);
printf("\nPlease enter the employee's Home address: ");
scanf("%s",&employee[a].address);
fprintf(fptr,"Employees address is: %s\r\n",employee[a].address);
printf("\nPlease enter the employee's department number: ");
scanf("%s",&employee[a].department);
fprintf(fptr,"Employees department is: %s\r\n",employee[a].department);
printf("\nPlease enter the employee's duration: ");
scanf("%s",&employee[a].duration);
fprintf(fptr,"Employees duration is: %s\r\n",employee[a].duration);
a++;
fclose(fptr);
goto CASE;
}
答案 0 :(得分:5)
以append
模式打开文件,而不是write
模式。
fptr=fopen("program.bin","wb");
此语句以program.bin
binary
模式打开文件write
。此模式表示每次打开文件时,文件的初始内容都将被截断。
您应该使用:
fptr=fopen("program.bin","ab");
以append
模式打开文件。
有关详细信息,请访问this link
答案 1 :(得分:2)
您每次都会覆盖文件的内容,因为您正在使用模式w
来编写文件,该文件从头开始重写文件。如果您只想将数据附加到文件的末尾,则应使用模式a
,如下所示:
fptr=fopen("program.bin","ab");
// ^ Using 'append' mode, rather than 'write' mode.