我在一个有 3 个类似结构的程序中工作。
typedef struct{
int id;
Person p;
}Client;
typedef struct{
int id;
Person p;
}Employee;
typedef struct{
int id;
Person p;
}Provider;
Run Code Online (Sandbox Code Playgroud)
制作的数据保存在三个不同的文件中。函数使用的大部分信息来自Person p;并且都是相似的(制作客户/员工/提供商,列出它们等)。问题是,因为它们是三种不同的结构,所以我必须为每个作业重复代码 3 次以从每个人中提取信息或制作数组以对文件进行排序。我想不出使用正确类型的单个代码来避免问题的方法。示例代码:
`
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;
}
Run Code Online (Sandbox Code Playgroud)
如果所有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;
Run Code Online (Sandbox Code Playgroud)
然后:
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;
}
Run Code Online (Sandbox Code Playgroud)