I'm looking for an easier way to maintain a code that generate CSV file.
Currently, each line in the CSV file is written in the following way:
fprintf(pCsvFile,"%s,%s,%d,%d,%d",param->a, param->b, param->c, param->d, param->e);
In reality I have around 20 different values from different types that I'm writing in every CSV file row, and as you can guess its start getting really difficult to maintain the code (adding or removing parameters).
Is there any clever way to do it in C language? Thanks.
This looks like a job for a tagged union. Here is an example of how to write more dynamic records.
#include <limits.h>
#include <stdio.h>
#define FIELD_COUNT 20
enum Kind {
String,
Int,
Float,
};
union Value {
const char* s;
int i;
float f;
};
struct Tagged_Union {
enum Kind kind;
union Value value;
};
void print_field(struct Tagged_Union tg)
{
switch (tg.kind) {
case String:
// to keep with the RFC4180 "standard," this is
// incorrect, but may not matter for your use case.
printf("%s", tg.value.s);
break;
case Int:
printf("%d", tg.value.i);
break;
case Float:
printf("%f", tg.value.f);
}
}
int main()
{
struct Tagged_Union tg[FIELD_COUNT];
// fill in your data
int i = 0;
for (; i < FIELD_COUNT; ++i) {
if (!i) {
printf(",");
}
print_field(tg[i]);
}
printf("\n");
}
Well, this will only print one record, but I hope you could see how this could be applied for your use case.