Using filename generated with mkstemp

The function mkstemp()

generates a unique temporary file name from the template, creates and opens the file, and returns the open file descriptor for the file. The last six characters of the pattern must be "XXXXXX" and are replaced with a string that makes the filename unique. Since it will be modified, the template does not need to be a string constant, but must be declared as a character array.

After replacing the template with a string that makes the filename unique, I save that string for future reference. Here I am facing some weird problem that I do not seem to wrap my head around. I can print the correct file name in my terminal, see the file in my explorer, and open it to see the correct content, but when I include the line as part of a command to execute with popen()

, I get a pointer to an empty file. When I hard-code the tempory filenames back into my code and run again, I get the correct result I expect. Is there something I am missing or missing? Here's a snippet of code:

char tmpname[] = "tmp.XXXXXX";
FILE *fpt = fdopen(mkstemp(tmpname), "w");
string saved_tmpname(tmpname);
// blah
// write to file
// blah blah
const string command = "mycommand " + saved_tmpname;
cout << command << endl; // prints correctly
FILE *fpipe = popen(command.c_str(), "r");
if (fpipe == NULL) {
  perror(command.c_str());
}
char buff[4096];
while (fgets(buff, 4096, fpipe)) {
  // we don't get here!
}

      

+3


source to share


1 answer


From the man page for mkstemp

:

The file is opened open (2) O_EXCL , ensuring that the caller is the process that creates the file.



The O_EXCL flag prevents you from opening the file again. This is fine as this is a temporary file - only one process (the creator) should have access to it. Temporary files sometimes contain sensitive data.

+4


source







All Articles