Boost logo

Boost :

From: Lars Gullik Bjønnes (larsbj_at_[hidden])
Date: 2005-01-29 22:16:13


larsbj_at_[hidden] (Lars Gullik Bjønnes) writes:

| The argument is not "shells do it that way". But "cp" does it that
| way. "cp" is not a shell it is a program specialized for copying
| files. Also that by not allowing overwrite of existing files it opens
| up for a race.

btw. There already is a race in the copy_file code: between that stat
of the source file and the opening of the source file. This can be
avoided by using fstat instead of stat.

Feeble attempt at solving that prob and makeing clobbering optional:

void copy_file(string const & source, string const & target, bool noclobber = true)
{
        int const infile = ::open(source.c_str(), O_RDONLY);
        if (infile == -1) {
                throw string("boost::filesystem::copy_file");
        }

        struct stat source_stat;
        int const ret = ::fstat(infile, &source_stat);
        if (ret == -1) {
                ::close(infile);
                throw string("boost::filesystem::copy_file");
        }

        int const flags = O_WRONLY | O_CREAT | (noclobber ? O_EXCL : O_TRUNC);

        int const outfile = ::open(target.c_str(), flags, source_stat.st_mode);
        if (outfile == -1) {
                ::close(infile);
                throw string("boost::filesystem::copy_file");
        }

        std::size_t const buf_sz = 32768;
        char buf[buf_sz];
        ssize_t in = -1;
        ssize_t out = -1;

        while (true) {
                in = ::read(infile, buf, buf_sz);
                if (in == -1) {
                        break;
                } else if (in == 0) {
                        break;
                } else {
                        out = ::write(outfile, buf, in);
                        if (out == -1) {
                                break;
                        }
                }
        }

        ::close(infile);
        ::close(outfile);

        if (in == -1 || out == -1)
                throw string("boost::filesystem::copy_file");
}

-- 
	Lgb

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