C++ ofstream delete and cleanup

删除回忆录丶 提交于 2019-12-02 08:44:48

问题


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).

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


回答1:


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

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.)



来源:https://stackoverflow.com/questions/15086054/c-ofstream-delete-and-cleanup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!