sprintf(filename, "%s%d", base, number);
Ah, yes. Though remember sprintf() does not calculate for buffer overflow. sprintf() doesn't flush any file buffer, in fact it doesn't have any buffer associated with it. sprintf() operates on a character buffer (not quite the same thing). If you overflow that buffer you can crash the system.
A safer version of sprintf() is snprintf() which unfortunately isn't very standard yet. It appears in various forms from many compiler vendors and was finally standardized in C99 and will hopefully make it as part of standard C++ in the next standard of C++. Until then you just have to dig up the unstandard version of it if you have one.
If you have no unstandard version of snprintf() you're sort of out of luck. You can of course always write your own version of sprintf() but it can be quite tricky unless you have your compiler's version of sprintf().
Here is an open-source version of snprintf() and others if interested:
snprintf.c - a portable implementation snprintf (etc...)
Writing your own version of itoa() on the contrary is quite simple. Just for reference, here is an example of how itoa() works:
#include <stdio.h>
//#include <string.h>
// Function declarations
// typedef __w64 unsigned int size_t
size_t strlen(const char *);
char *strrev(char *);
char *itoa(int, char *, int);
int main() {
int num = 123;
char buf[5];
itoa(num, buf, 10);
printf("%s\n", buf);
return 0;
}
size_t strlen(const char *string) {
const char *s;
s = string;
while (*s)
s++;
return s - string;
}
char *strrev(char *str) {
char *p1, *p2;
if (!str || !*str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
char *itoa(int n, char *s, int b) {
static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
int i=0, sign;
if ((sign = n) < 0)
n = -n;
do {
s[i++] = digits[n % b];
} while ((n /= b) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
return strrev(s);
}
It isn't perfect, but it gets the job done.
-
Stack
Overfow