std :: tmpfile()没有选择TMPDIR位置

时间:2016-07-09 17:30:33

标签: c++ c++11 temporary-files tmp

我使用std :: tmpfile()创建临时文件,但我想使用/ tmp以外的位置。我导出$ TMPDIR指向新位置,但是std :: tmpfile()没有选择新位置。

如何在/ tmp以外的文件夹中使用std :: tmpfile()创建临时文件?

1 个答案:

答案 0 :(得分:1)

快速测试计划

#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