Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate temporary file/folder c++ GTEST

Tags:

c++

googletest

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.

like image 425
Lorac Avatar asked Jul 15 '16 14:07

Lorac


2 Answers

Googletest now includes testing::TempDir(), however it just returns /tmp/ or the platform specific equivalent, it doesn't do any cleanup.

like image 124
Grumbel Avatar answered Sep 22 '22 02:09

Grumbel


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.

like image 39
Kitlith Avatar answered Sep 22 '22 02:09

Kitlith