Home > Net >  What does the XXXXXX in an sprintf format argument of "/tmp/%s-XXXXXX" mean?
What does the XXXXXX in an sprintf format argument of "/tmp/%s-XXXXXX" mean?

Time:07-16

In the following code, it seems XXXXXX asks to generate random characters to replace it. What does XXXXXX mean here? Is this some special reserved symbol in sprintf?

sprintf(tempName, "/tmp/%s-XXXXXX", filename.c_str());

CodePudding user response:

More context would help, but judging from the array name tempName, this sprintf call is probably composing a template for use with mktemp(), mkstemp(), mkdtemp() or a similar function.

The Xs do not have any particular meaning for sprintf, but are interpreted by the next function called with tempName.

These POSIX functions are declared in <unistd.h>:

SYNOPSIS

#include <unistd.h>

char *mktemp(char *template);
int mkstemp(char *template);
char *mkdtemp(char *template);

DESCRIPTION

The mktemp() function takes the given file name template and overwrites a portion of it to create a file name.

This file name is guaranteed not to exist at the time of function invocation and is suitable for use by the application. The template may be any file name with some number of Xs appended to it, for example /tmp/temp.XXXXXX. The trailing Xs are replaced with a unique alphanumeric combination. The number of unique file names mktemp() can return depends on the number of Xs provided; six Xs will result in mktemp() selecting one of 56800235584 (626) possible temporary file names.

The mkstemp() function makes the same replacement to the template and creates the template file, mode 0600, returning a file descriptor opened for reading and writing. This avoids the race between testing for a file's existence and opening it for use.

The mkdtemp() function makes the same replacement to the template as in mktemp() and creates the template directory, mode 0700.

Note that unless tempName was allocated with enough space for filename.c_str() plus 12 characters and a null terminator, using snprintf() is highly recommended to avoid undefined behavior, and limit the number of characters from filename.c_str() to make sure all Xs are present at the end:

char tempname[32];
snprintf(tempName, sizeof tempName, "/tmp/%.19s-XXXXXX", filename.c_str());
  • Related