删除二进制文件中的条目时出错

时间:2013-05-05 11:47:23

标签: c file

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();
            }

2 个答案:

答案 0 :(得分:0)

scanf函数采用格式字符串,后跟目标变量的地址。因此,假设您已将empid定义为int,则需要更改

scanf("%d",empid);

scanf("%d", &empid);

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

答案 1 :(得分: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[],则在将其与员工ID进行比较时,应使用atoi()将所需的ID转换为整数:

if(e.userid!=atoi(empid))