我在一个有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;
}
如果所有的struct
S皆相等,就可以共享一个基础struct
,并typedef
在你的文件,是这样的:
/* 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句