I have been given a project which monitors 3 apartment's water usages. I need to write these usages into a binary file and the binary filename must be different for each apartment: The names must be:
"compact_usages_%d.bin"
where %d is either apartment 1, 2 or 3 and I am not allowed to use the following code:
sprintf(filename, "compact_usage_%d.bin", apartment);
Is there another way to do this without using sprintf() ?
Since your substitution is always the same size and is a constant offset from the beginning of the string, you can use array arithmetic to edit it directly:
#define BASE "compact_usage_"
#define END ".bin"
#define NAME BASE "0" END
int main (void) {
static char filename[] = NAME;
unsigned char aptNo = 1;
filename[sizeof(BASE)-1] = '0' + aptNo;
printf("%s\n", filename);
return 0;
}