0

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() ?

Antony Nepgen
  • 107
  • 2
  • 8

2 Answers2

3

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;
}
teach stem
  • 132
  • 6
1

Sure:

strcpy(filename, "compact_usage_");
switch (apartment) {
    case 1: strcat(filename, "1"); break;
    case 2: strcat(filename, "2"); break;
    case 3: strcat(filename, "3"); break;
    default: abort();
}
strcat(filename, ".bin");

Or:

strcpy(filename, "compact_usage_0.bin");
filename[14] += apartment;

Or:

const char *filenames[] = {
    "compact_usage_1.bin",
    "compact_usage_2.bin",
    "compact_usage_3.bin",
};

strcpy(filename, filenames[apartment - 1]);
melpomene
  • 84,125
  • 8
  • 85
  • 148