This program is designed to generate unique names every time tmp_name is called. To test it, we decided to print a couple of names. Yet our test isn't working. Why?
1 /************************************************
2 * test the tmp_name function. *
3 ************************************************/
4 #include <iostream>
5 #include <cstdio>
6 #include <cstring>
7 #include <sys/param.h>
8 /************************************************
9 * tmp_name -- return a temporary file name. *
10 * *
11 * Each time this function is called, a new *
12 * name will be returned. *
13 * *
14 * Returns *
15 * Pointer to the new file name. *
16 ************************************************/
17 char *tmp_name(void)
18 {
19 // The name we are generating
20 static char name[MAXPATHLEN];
21
22 // The directory to put the temporary file in
23 const char DIR[] = "/var/tmp/tmp";
24
25 // Sequence number for last digit
26 static int sequence = 0;
27
28 ++sequence; /* Move to the next file name */
29
30 std::sprintf(name, "%s.%d", DIR, sequence);
31 return(name);
32 }
33
34 int main()
35 {
36 // The first temporary name
37 char *a_name = tmp_name();
38
39 // The second temporary name
40 char *b_name = tmp_name();
41
42 std::cout << "Name (a): " << a_name << endl;
43 std::cout << "Name (b): " << b_name << endl;
44 return(0);
45 }