-2
system("cls");
            another = 'y';
            while(another == 'y')
            {
                printf("\nEnter name of employee to delete ");
                scanf("%s",empname);
                ft = fopen("Temp.dat","wb");
                rewind(fp);
                while(fread(&e,recsize,1,fp) == 1)
                {
                    if(strcmp(e.name,empname) != 0)
                    {
                        fwrite(&e,recsize,1,ft);
                    }
                }
                fclose(fp);
                fclose(ft);
                remove("EMP.DAT");
                rename("Temp.dat","EMP.DAT");
                fp = fopen("EMP.DAT", "rb+");
                printf("Delete another record(y/n)");
                another = getche();
            }

这是使用员工姓名从 c 中的二进制文件中删除条目的代码!但是当我想通过 emp id 删除它时,它不会删除条目,而是删除文件的所有内容!

case '4':
            system("cls");
            another = 'y';
            while(another == 'y')
            {
                printf("\nEnter employee id to delete ");
                scanf("%d",&empid);
                ft = fopen("Temp.dat","wb");
                rewind(fp);
                while(fread(&e,recsize,1,fp) == 1)
                {
                    if(e.userid!=empid)
                    {
                        fwrite(&e,recsize,1,ft);
                    }
                }
                fclose(fp);
                fclose(ft);
                remove("EMP.DAT");
                rename("Temp.dat","EMP.DAT");
                fp = fopen("EMP.DAT", "rb+");
                printf("Delete another record(y/n)");
                another = getche();
            }
4

2 回答 2

0

scanf函数采用格式字符串,后跟目标变量的地址。所以,假设你已经定义empidint,你需要改变

scanf("%d",empid);

scanf("%d", &empid);

您没有在按名称删除的代码中看到问题,因为empname它已经是指向字符的指针。你确实记得为它分配内存,对吧?

于 2013-05-05T11:57:46.353 回答
0

我相信scanf("%d", empid);是错误的。如果它被定义为int empid;你应该至少得到一个编译警告:

warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]

读取整数的正确方法是:

scanf("%d", &empid);
            ^

如果empid定义为char*或者char[]您应该在将所需的 idatoi()与员工的 id 进行比较时将其转换为整数:

if(e.userid!=atoi(empid))
于 2013-05-05T11:58:53.737 回答