快速测试程序
#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;
}
和一个 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) +++
确认,根据手册页,std::tmpnam 没有参考环境变量,它只使用常量P_tmpdir。
如果这纯粹是针对 Linux 的,您可以改用 mkstemp:
#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;
}
演示:
osmith@osmith-VirtualBox:~$ g++ -o test.exe test.cpp -std=c++14
osmith@osmith-VirtualBox:~$ ./test.exe
/var/tmp/testEFULD4