I need to generate temp file for a test. It looks like I can't use mkstemp
because I need the filename to have a specific suffix, but the rest of the filename I don't care. Is there a way in GTest to create a temporary file that handles the creation of the file plus the deletion at the end of the test.
The other approach would be to create my own class to do that.
Googletest now includes testing::TempDir()
, however it just returns /tmp/
or the platform specific equivalent, it doesn't do any cleanup.
You can use mkstemps on some systems, though it is non-standard. From the man page for mkstemp:
The mkstemps() function is like mkstemp(), except that the string in template contains a suffix of suffixlen characters. Thus, template is of the form prefixXXXXXXsuffix, and the string XXXXXX is modified as for mkstemp().
Therefore, you can use mkstemps somewhat like this:
// The template in use. Replace '.suffix' with your needed suffix.
char temp[] = "XXXXXX.suffix";
// strlen is used for ease of illistration.
int fd = mkstemps(temp, strlen(".suffix"));
// Since the template is modified, you now have the name of the file.
puts(temp);
You will need to keep track of the filename so that you can delete it at the end of the program. If you wanted to be able to put all of these files into, say, /tmp, you should be able to add "/tmp/" as a prefix. There doesn't appear for there to be a way for it to create a temporary directory, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With