避免使用类似的结构重复代码C

时间:2018-08-16 12:48:42

标签: c function struct

我正在一个程序中工作,我有3个类似的结构。

typedef struct{
  int id;
  Person p;
}Client;

typedef struct{
  int id;
  Person p;
}Employee;

typedef struct{
  int id;
  Person p;
}Provider;

所做的数据保存在三个不同的文件中。函数使用的大多数信息来自人p。而且都是相似的(创建客户/雇员/提供者,列出它们,等等)。 问题在于,由于它们是三种不同的结构,因此我必须为每个作业重复执行三次代码,以从每个Person中提取信息或创建数组以对文件进行排序。我无法以某种方式来避免使用正确类型的单个代码的问题。 示例代码:

`

int extractNameProvider(){
  FILE *arch;
  int ret=0;
  Provider pro;
  arch=fopen("fileP","rb");
  if(arch!=NULL){
    fread(&cli,sizeof(Provider),1,arch);
    printf("%s",pro.p.name);
    fclose(arch);
  }
  else{
    ret=-1;
  }
  return ret;
}

int extractNameClient(){
  FILE *arch;
  int ret=0;
  Client cli;
  arch=fopen("fileC","rb");
  if(arch!=NULL){
    fread(&cli,sizeof(Client),1,arch);
    printf("%s",cli.p.name);
    fclose(arch);
  }
  else{
    ret=-1;
  }
  return ret;
}

int extractNameEmployee(){
  FILE *arch;
  int ret=0;
  Employee emp;
  arch=fopen("fileE","rb");
  if(arch!=NULL){
    fread(&emp,sizeof(Employee),1,arch);
    printf("%s",emp.p.name);
    fclose(arch);
  }
  else{
    ret=-1;
  }
  return ret;
}

1 个答案:

答案 0 :(得分:4)

如果所有struct都相同,则可以在文件中共享基本structtypedef,例如:

/* base.h */
struct BasePerson{
  int id;
  Person p;
};

/* client.h */
#include "base.h"
typedef struct BasePerson Client;

/* employee.h */
#include "base.h"
typedef struct BasePerson Employee;

/* provider.h */
#include "base.h"
typedef struct BasePerson Provider;

然后:

int extractNamePerson(char *file){
  FILE *arch;
  int ret=0;
  struct BasePerson person;
  arch=fopen(file,"rb");
  if(arch!=NULL){
    fread(&person,sizeof(struct BasePerson),1,arch);
    printf("%s",person.p.name);
    fclose(arch);
  }
  else{
    ret=-1;
  }
  return ret;
}