std :: tmpfile()未选择TMPDIR位置 [英] std::tmpfile() not picking TMPDIR location

查看:58
本文介绍了std :: tmpfile()未选择TMPDIR位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

How to create temporary files with std::tmpfile() in a folder other than /tmp?

推荐答案

快速测试程序

#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 这是一个常量.

confirms that, per the man page, no environment variables are consulted by std::tmpnam, it only uses P_tmpdir which is a constant.

如果这仅适用于Linux,则可以改用 mkstemp :

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;
}

演示:

osmith@osmith-VirtualBox:~$ g++ -o test.exe test.cpp -std=c++14
osmith@osmith-VirtualBox:~$ ./test.exe
/var/tmp/testEFULD4

这篇关于std :: tmpfile()未选择TMPDIR位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆