I am working on some code that writes output to different streams/files depending on which function of the family is called by the user. I am trying to do this as succinctly as possible and not have a ton of unused information in the struct I'm using to call the actual write function. Currently I have this as a basic structure (this is just a rough draft):
typedef int (*Write_Out) (char *src, size_t len);
typedef struct s_vas_info
{
char **ret;
int prev_size;
} t_vas_info;
typedef struct s_vd_info
{
int fd;
} t_vd_info;
typedef struct s_vf_info
{
FILE *fp;
} t_vf_info;
typedef struct s_vsn_info
{
size_t size;
char * restrict str;
} t_vsn_info;
typedef struct s_writer
{
int curr;
Write_Out ft_write;
} t_writer;
Where Write_Out will point to the function that sends output to the right destination, t_writer will hold all information to do this and the other structs are used when the corresponding function is called. Now I'd really like for the s_writer type to have one more member that contains one of the other struct types (directly if possible, I'm not looking to solve this with pointers and casts if at all avoidable). I am pretty new at this so I don't know if this is possible (either with these or other data types). Any help would be appreciated!
For this you want a union
.
A union
is similar to a struct
except that it only holds one if its members at any given time.
typedef struct s_writer
{
int curr;
Write_Out ft_write;
int active;
union {
struct {
char **vas_ret;
int vas_prev_size;
};
struct {
int vd_fd;
};
struct {
FILE *vf_fp;
};
struct {
size_t vsn_size;
char * restrict vsn_str;
};
};
} t_writer;
You can use the active
field to determine which union field contains the actual data. Also note that the union and its internal structs have no name, so their members can be accessed directly as members of t_writer
;