The mkstemp()
function generates a unique temporary filename from template, creates and opens the file, and returns an open file descriptor for the file. The last six characters of template must be "XXXXXX" and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array.
After template is replaced with a string that makes the filename unique, I save the string to later use. This is where I'm encountering a strange problem I can't seem to wrap my head around. I can print the correct filename to my terminal, see the file in my file explorer and open it to see the correct contents, but when I include the string as part of a command to execute with popen()
I get a pointer to an empty file. When I hard code the names of the tempory files back into my code however and run again, I get the correct result I am expecting. Is there something I'm overlooking or missing? Here is a code snippet:
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!
}