删除文件中的记录(C编程)

时间:2016-06-30 03:45:21

标签: c file

我是C的新手。目前,我正在学习文件管理。 为了进一步了解文件,我想创建一个员工数据库系统,用户可以在其中创建,删除,更新或检索员工记录。首先,我创建了一个结构,其中包含员工的变量,如ID,名字,姓氏和薪水,然后是创建记录的函数,但是存在问题。我知道如何从文件中搜索(使用ID号),但我不知道如何删除特定记录。

(我很抱歉,因为我不小心删除了我的DeleteFunction,因此无法在我的代码中显示该特定功能)

  • 据我所知,我的代码运行良好,但您会发现任何错误

所以这是我的代码:

   #include <stdio.h>
   #include <string.h>

   typedef struct employee{
   int id;
   char name[40];
   float pay;
   }EMP;

  void CreateEmployee(struct employee [] );
  void DisplayRecord();

  int main() {
      EMP e[20];
      CreateEmployee(e);
      //return 0;
    DisplayRecord();
    return 0;
}


void CreateEmployee(struct employee x[]){
char choice ='y';
int i=0;

//EMP employee[20];


FILE *fp;
fp = fopen("employee.txt","a");
if (fp==NULL){
    printf("File not created");
}
while((choice == 'Y') || (choice =='y')){
    printf("Enter the employee's id:");
    scanf("%i",&x[i].id);
    fprintf(fp,"%i\t",x[i].id);

    printf("\nEnter the employee's name:");
    scanf("%s",x[i].name);
    fprintf(fp,"%s\t",x[i].name);

    printf("\nEnter the employee's pay:");
    scanf("%f",&x[i].pay);
    fprintf(fp,"%.2f\t\n",x[i].pay);

    printf("\nEnter another employee?\n");
    printf("Y - Yes     N - No:\n");

    scanf("\n%c",&choice);
     i++;
}

fclose(fp);

}

void DisplayRecord(){

EMP temp;

FILE *fp = fopen("employee.txt", "r");

if(fp != NULL)
{

    while( !feof(fp) )
    {
        fscanf(fp, "%i %s  %f", &temp.id, temp.name, &temp.pay);

        printf("%i %s %f\n",temp.id, temp.name, temp.pay);
    }

    fclose(fp);
    }
else
 {
    printf("An error occurred opening the file\n");
 }
}

我还不知道如何使用随机访问文件;这就是我目前使用顺序访问的原因。

1 个答案:

答案 0 :(得分:2)

要删除记录,您有以下几种选择:

  1. 通过在每条记录中添加deleted字段进行准备,并在阅读记录时跳过具有deleted == true的字段。要实际删除记录,请将其deleted标记设置为true并保存。

  2. 读取数据文件并将所有记录写入临时文件,但要删除的文件除外。最后,将临时文件重命名为employees.txt

  3. 切换到真实的数据库来管理记录,因为所有典型的操作都快速而简单。

  4. 顺便说一下,你还没有说为什么你喜欢C作为编程语言。如果是因为你可以快速完成任务,那么只要你的程序变得更大,你就会失望,因为你必须在代码中明确地进行内存管理和错误处理。并且,C使你很容易在脚下射击(因此你的程序崩溃并且不起作用),因为它没有内置的内存保护。因此,在完全爱上这种语言之前,先看看周围是否能找到更好的东西。