可以尝试以下方法:
在写入时使用struct 了解数据类型
typedef enum { String, Int, Char} datatype;
struct record{
datatype dt;
void* data;
};
int myfprintf(FILE* stream, struct record* rec){
switch(rec->dt){
case Char: return fprintf(stream, "%c", *((char*)(rec->data)));
case Int: return fprintf(stream, "%d", *((int*)rec->data));
case String: return fprintf(stream, "%s", (char*)rec->data);
//....
default: return fprintf(stream,"%s", "Error");
}
}
然后使用myprintf传递流和record类型的数据
或者,您也可以以类似的方式使用union
使用C11,您可以执行以下操作:-(取自here):
#define printf_dec_format(x) _Generic((x), \
char: "%c", \
signed char: "%hhd", \
unsigned char: "%hhu", \
signed short: "%hd", \
unsigned short: "%hu", \
signed int: "%d", \
unsigned int: "%u", \
long int: "%ld", \
unsigned long int: "%lu", \
long long int: "%lld", \
unsigned long long int: "%llu", \
float: "%f", \
double: "%f", \
long double: "%Lf", \
char *: "%s", \
void *: "%p")
#define fprint(stream, x) fprintf(stream,printf_dec_format(x), x)
fprint(stdin,(char *)"P0W"); // for string literal