问题
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.new—commit 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