Boost logo

Boost :

From: Vladimir Prus (ghost_at_[hidden])
Date: 2004-07-16 02:50:48


David Abrahams wrote:

> > However, mkstemp(3) not only generates a unique filename but it also
> > opens the corresponding file and returns the file descriptor. You'd
> > have to close the file, possibly remove it, and then pass the filename
> > to the constructor of your stream which will create and open the file
> > again. That sounds like a hack to me and may not be portable.
>
> And I think it undermines the big reason tmpnam is not recommended:
> someone can come along and grab the same name and you will overwrite
> their file by mistake.

Actually, even worse: somebody can create a link from /tmp/xyz
to /your/home/dir/the_most_important_file and when you open /tmp/xyz for
writing, you will wipe the important file of yours. This is in fact much
worse then overwriting some other user's temporary file -- which I think is
not possible on Unix.

The right solution in Unix is to pass O_EXCL|O_CREAT flags to the 'open'
system call -- which will make sure that the file does not exist. Or you can
use mkstemp, as Martin says.

Something like this will do:

    char name[] = "testXXXXXX";
    int fd = mkstemp(name);
    std::ofstream ofs(name);
    ofs << "foo";

It is also possible to make OS remove the file no matter what happens to your
program by calling "unlink(name)" while the file is still open. However, this
will remove the file from directory listing, so all streams must be opened
before calling unlink, like this:

    char name[] = "testXXXXXX";
    int fd = mkstemp(name);
    std::ofstream ofs(name);
    std::ifstream ifs(name);
    unlink(name);
    ofs << "foo" << std::flush;
    std::cout << "Name is: " << name << "\n";
    std::cout << "Content is : " << ifs.rdbuf() << "\n";

- Volodya

 


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk