gpt4 book ai didi

c - fprintf覆盖C中的其他数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:53 27 4
gpt4 key购买 nike

我正在尝试将 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;
}

最佳答案

append 模式而非write 模式打开文件。

fptr=fopen("program.bin","wb");

此语句以binary write 模式打开文件program.bin。这种模式意味着每次打开文件时,文件的初始内容都会被截断。

你应该使用:

fptr=fopen("program.bin","ab");append 模式打开文件。

有关更多详细信息,请访问 this link

关于c - fprintf覆盖C中的其他数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23079711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com