C ++的流删除和清理 [英] C++ ofstream delete and cleanup

查看:129
本文介绍了C ++的流删除和清理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C ++的stream,有时必须清理 - 我写的文件应该删除,类删除和清理。

I am writing a C++ ofstream that sometimes must be cleaned up - the file I am writing to should be deleted and the class deleted and cleaned up.

如何? (除非关闭它并按名称删除它)。

How? (Except closing it and deleting it by name).

(至少文件不应该与打开的位置和文件名一起存在 - tempfile目录可以OK)

(At least the file should not exist with the intended location and filename with which it was opened - tempfile directory could be OK)

推荐答案

据我所知,没有其他办法。关闭文件并使用
remove

As far as I know, there is no other way. Close the file and use remove with its name.

这可能最好由某种类型处理的RAII类;
我经常使用 OutputFile 类,隐式转换
std :: ostream& (用于输出)。构造函数使用文件的名称
;有一个 commit 函数关闭文件
,但如果析构函数在 commit 之前被调用,不仅
关闭文件,而且删除它。类似地,有一个
UpdateFile 类,它打开
filename .new commit 然后重命名
filename c $ c> filename .bak

(删除任何以前存在的文件),
移动 filename .new
filename 。而析构函数删除
filename .new 。 (变体检查
新内容是否与 commit 中的旧内容不同,以便
文件时间戳不会更改,如果没有更改在内容中。)

This is probably best handled by some sort of RAII class; I regularly use an OutputFile class, which converts implicitly to std::ostream& (for output). The constructor takes the name of a file; there is a commit function which closes the file, but if the destructor is called before commit, it not only closes the file, but deletes it. Similarly, there is an UpdateFile class, which opens filename.newcommit then renames filename to filename.bak (deleting any previously existing file with that name), and moves filename.new to filename. And the destructor deletes filename.new. (A variant checks whether the new contents are different from the old in commit, so that the file timestamp won't change if there's no change in contents.)

这篇关于C ++的流删除和清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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