问题
I am using std::tmpfile() to create temporary files, but I want to use the location other than /tmp. I am exporting $TMPDIR to point to the new location, but std::tmpfile() doesn't pick the new location.
How to create temporary files with std::tmpfile() in a folder other than /tmp?
回答1:
A quick test program
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
int main()
{
const char* tf = std::tmpnam(nullptr);
std::cout << "tmpfile: " << tf << '\n';
return 0;
}
and an ltrace
osmith@osmith-VirtualBox:~$ ltrace ./test.exe
__libc_start_main(0x400836, 1, 0x7ffedf17e178, 0x4008e0 <unfinished ...>
_ZNSt8ios_base4InitC1Ev(0x601171, 0xffff, 0x7ffedf17e188, 160) = 0
__cxa_atexit(0x400700, 0x601171, 0x601058, 0x7ffedf17df50) = 0
tmpnam(0, 0x7ffedf17e178, 0x7ffedf17e188, 192) = 0x7fe4db5a0700
_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc(0x601060, 0x400965, -136, 0x7fe4db2d13d5) = 0x601060
_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc(0x601060, 0x7fe4db5a0700, 0x601060, 0xfbad2a84) = 0x601060
_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c(0x601060, 10, 0x7fe4db91d988, 0x57474f44696b656ctmpfile: /tmp/filekiDOGW
) = 0x601060
_ZNSt8ios_base4InitD1Ev(0x601171, 0, 0x400700, 0x7fe4db59fd10) = 0x7fe4db922880
+++ exited (status 0) +++
confirms that, per the man page, no environment variables are consulted by std::tmpnam
, it only uses P_tmpdir
which is a constant.
If this is purely for Linux, you could use mkstemp
instead:
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <unistd.h>
int main()
{
char tmpl[] = "/var/tmp/testXXXXXX";
int f = mkstemp(tmpl);
if (f < 0) {
std::cerr << "mkstemp failed\n";
return 1;
}
std::cout << tmpl << '\n';
close(f);
return 0;
}
Demo:
osmith@osmith-VirtualBox:~$ g++ -o test.exe test.cpp -std=c++14
osmith@osmith-VirtualBox:~$ ./test.exe
/var/tmp/testEFULD4
来源:https://stackoverflow.com/questions/38284450/stdtmpfile-not-picking-tmpdir-location