Skip to content

File::create fails on hidden files on Windows #115745

Closed
@ChrisDenton

Description

@ChrisDenton

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 and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ioArea: `std::io`, `std::fs`, `std::net` and `std::path`C-bugCategory: This is a bug.O-windowsOperating system: WindowsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions