Description
Reported on discord, using OpenOptions::new().write(true).create(true).truncate(true).open(&path)
will fail on Windows if the file is hidden. This also affects methods like File::create
or fs::write
that open the file the same way.
The reason for this is that we use CREATE_ALWAYS
, which has strange behaviour:
If
CREATE_ALWAYS
andFILE_ATTRIBUTE_NORMAL
are specified,CreateFile
fails and sets the last error toERROR_ACCESS_DENIED
if the file exists and has theFILE_ATTRIBUTE_HIDDEN
orFILE_ATTRIBUTE_SYSTEM
attribute. To avoid the error, specify the same attributes as the existing file.
So to make it work the caller needs to match the requested attributes to the existing attributes at the time of opening.
Possible solution
It was suggested we could instead use OPEN_ALWAYS
and then manually truncate the file using SetFileInformationByHandle
to set the FILE_ALLOCATION_INFO
to zero.