【发布时间】:2021-09-28 21:24:39
【问题描述】:
我正在为 s 献血系统编写代码。我目前正在为删除捐赠者记录功能而苦苦挣扎。
删除记录功能是删除一个给定名字的捐赠者的记录。如果文件中有两个或多个同名记录,则程序会要求提供手机号码。虽然可能有不止一个人同名,但每个人都有一个唯一的手机号码。
我的问题是多条记录使用同名时,删除了错误的记录。
如果只有一条具有该名称的记录,则程序会以所需的方式删除该记录。
(变量 i 全局声明为 int i)
这里是删除功能
void delete(struct blood *b,int n)
{
char name[50];
int phone;
int found=0;
int c=0;
FILE *fp = fopen("bloodrecord.txt", "r");
FILE *fp1 = fopen("temp.txt", "w");
printf("\nEnter Name: ");
scanf("%s", name);
printf("---------------------------------------------\n");
while(fread(&b[i],sizeof(struct blood),1,fp))
{
if(strcmpi(b[i].name,name)==0)
{
c=c+1;
printf("\nName: %s\n",b[i].name);
printf("Age: %d\n", b[i].age);
printf("Mobile no.: %d\n", b[i].phone);
printf("Blood group: %s\n", b[i].bg );
printf("Weight: %d\n", b[i].weight);
printf("Sex: %s\n",b[i].sex);
printf("Address: %s\n",b[i].add);
printf("\n");
if (c==1)
{
found=1;
}
else if(c>1)
{
printf("\nThere are more than one occurences of this name in the records\n");
printf("\nPlease enter the mobile number of the donor: ");
scanf("%d", &phone);
if (b[i].phone == phone)
{
found=1;
}
}
}
else
fwrite(&b[i],sizeof(struct blood),1,fp1);
}
fclose(fp);
fclose(fp1);
if (found==1)
{
fp1 = fopen("temp.txt", "r");
fp = fopen("bloodrecord.txt", "w");
while(fread(&b[i],sizeof(struct blood),1,fp1))
{
fwrite(&b[i],sizeof(struct blood),1,fp);
}
fclose(fp);
fclose(fp1);
}
else
{
printf("\n\aRECORD DOES NOT EXIST.\n");
}
printf("RECORD SUCCESSFULLY DELETED");
getchar();
getchar();
}
【问题讨论】:
-
我认为您需要分多个步骤执行此操作:首先找到并计算“命中”的数量。然后在第二步中,根据条件查找和擦除。
-
scanf(" %[^\n]s", name);与dangerous asgets相同,因为您可以轻松读取超出缓冲区容量的数据。还知道%[]和%s是两个独立的转换说明符,您不要将它们组合在一起。始终指定最大长度%49[^\n],即缓冲区的长度 - 1。(考虑使用涉及fgets的更强大的方法)。 -
这些是文本文件吗(.txt 扩展名暗示了这一点)?如果是这样,那么
fwrite不合适。 -
Aditya Ranjan,谁或什么文字建议
scanf(" %[^\n]s", name);? -
@Aditya Ranjan - 作为函数的第一个参数传递的内容。
i的定义及其在调用时的值是什么?
标签: c file pointers struct record