constantinpape / z5

Lightweight C++ and Python interface for datasets in zarr and N5 format
MIT License
110 stars 27 forks source link

Existing files are not overwritten when creating a new `w`-mode file #217

Open nsoblath opened 1 year ago

nsoblath commented 1 year ago

The w mode for files should allow existing files to be overwritten when creating a new file. However, that doesn't appear to be respected.

I'm creating filesystem-based files. In z5::handle::File, the create() method has a couple checks before creating the file:

        inline void create() const {
            if(!mode().canCreate()) {
                const std::string err = "Cannot create new file in file mode " + mode().printMode();
                throw std::invalid_argument(err.c_str());
            }
            if(exists()) {
                throw std::invalid_argument("Creating new file failed because it already exists.");
            }
            createDir();
        }

The first check guarantees the file is a writeable file, and that looks fine. The second check guarantees that the file doesn't already exist. This if statement doesn't respect the w mode and treats all writeable files as if they're w_m or a mode files.

A possible solution would be to add an inner check:

            if(exists()) {
                if(mode().shouldTruncate()) {
                    [remove existing file]
                } else {
                    throw std::invalid_argument("Creating new file failed because it already exists.");
                }
            }