Re: Simple question about exit(1)
On Jun 18, 7:13 pm, Paavo Helde <myfirstn...@osa.pri.ee> wrote:
Christian Hackl <ha...@sbox.tugraz.at> wrote in news:hvffg9$e0h$1
@news.eternal-september.org:
http://www.cplusplus.com/reference/clibrary/cstdlib/exit/
Actually, I don't know why they claim that "temporary files"
are deleted. That's a very misleading statement. AFAIK,
neither Windows nor Unix/Linux can handle filesystems that
have a concept of temporary files that is not enforced only
by convention.
In Windows one can use the FILE_FLAG_DELETE_ON_CLOSE flag for
CreateFile() to have the file deleted on program exit. In
Linux/Unix one can achieve the same effect by opening a file,
then immediately unlink()-ing all references to it from the
disk directories. However, when one talks about "temporary
files" one probably means something else.
But these solutions don't work for standard streams, or at
least, the one for Windows doesn't (because the filebuf never
uses this flag when it does CreateFile).
Practically, too, it's not rare to want to close a temporary
file, then reopen it later.
It's possible to make this work, more or less, by registering
the temporary files with an object with static lifetime, which
deletes them in its destructor. In the case of Windows, you
still have to ensure that the file is closed first. Which
brings us to the one big problem with exit---it doesn't call the
destructors of local objects. So if you write something like:
void f()
{
std::string tmpname(getTempFileName());
std::fstream tmp(name.c_str());
TempFileManager::instance().register(tmpname);
// ...
if (something)
exit(1);
// ...
}
, the temp file will not get deleted.
One convention that I've used at times is that main() is always:
main(...)
{
try {
// actual code...
return errorStatus;
} catch ( int returnCode ) {
return returnCode;
}
}
Then, instead of calling exit(EXIT_FAILURE), you "throw
EXIT_FAILURE".
--
James Kanze