C ++:获取一个临时文件,跨平台 [英] C++: Getting a temporary file, cross-platform

查看:179
本文介绍了C ++:获取一个临时文件,跨平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个跨平台的方式来获取指定的临时文件。例如,在linux中,它位于 / tmp dir中,而在Windows中则位于一些名为Internet Explorer的临时目录中。



这是否存在跨平台(Boost?)解决方案?



EDIT



我需要这个文件存在,直到程序终止。 tmpfile()不保证。引用来自ccpreference:


当流关闭时,临时文件会自动删除 fclose

从该库的版本3,可以用于创建临时文件名。它还提供了一个清晰的解决方案。实际上,以下C ++代码应该与平台无关:

  // Boost.Filesystem需要VERSION 3 
#include< ; string>
#include< boost / filesystem.hpp>
boost :: filesystem :: path temp = boost :: filesystem :: unique_path();
const std :: string tempstr = temp.native(); //可选

文件系统路径对象 temp 可用于打开文件或创建子目录,而字符串对象 tempstr 提供与字符串相同的信息。有关详情,请参见 http://www.boost.org


I'm looking for a cross-platform way of getting designated a temporary file. For example in linux that would be in the /tmp dir and in Windows in some crappy named Internet Explorer temp dir.

Does a cross-platform (Boost?) solution to this exist?

EDIT:

I need this file to exist until the program terminates. tmpfile() does not guarantee that. Quoting from ccpreference:

The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally.

解决方案

The Boost Filesystem library, from version 3 of that library, can be used to create a temporary file name. It also offers a crisp solution. Indeed, the following C++ code should be platform independent:

// Boost.Filesystem VERSION 3 required
#include <string>
#include <boost/filesystem.hpp>
boost::filesystem::path temp = boost::filesystem::unique_path();
const std::string tempstr    = temp.native();  // optional

The filesystem path object temp can be used to open a file or create a subdirectory, while the string object tempstr offers the same information as a string. See http://www.boost.org for more details.

这篇关于C ++:获取一个临时文件,跨平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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