简体   繁体   中英

std::filesystem::remove_all fails on read-only file

I am trying to remove a complete git repository clone from my disk using std::filesystem::remove_all()

std::filesystem::remove_all( myRepoName );

This throws an exception

terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
  what():  filesystem error: cannot remove all: Input/output error [windex] 
[windex\.git\objects\pack\pack-6592b2cba8201deb33301b149bcb61af6b4be49b.idx]

This file is read-only. It can be deleted with no problem from windows explorer.

This in windows 10 and mingw g++ v11.2. So this seems to be a bug in the implementation of std::filesystem.

Any workaround available? Maybe std::filesystem::permissions https://en.cppreference.com/w/cpp/filesystem/permissions ?

Tried adding

    std::filesystem::permissions(
        "windex/.git/objects/pack/pack-3b1477e94a042244b9aed7021724d8a020be62c9.idx",
        std::filesystem::perms::others_all );

but still get same error and the file remains readonly.

After experimenting, found that owner_write does the job

This code solves the problem by changing the readonly permission of any file that fails to delete.

int count = 0;
while (count < 5)
{       
    try
    {
        std::filesystem::remove_all(myRepoName);
        break;
    }
    catch (std::filesystem::__cxx11::filesystem_error &e)
    {
        std::this_thread::sleep_for (std::chrono::milliseconds(250));
        std::string f ( e.what() );
        int p = f.find("[");
        p = f.find("[",p+1);
        f = f.substr(p+1);
        f = f.substr(0,f.length()-1);
        std::filesystem::permissions(
            f, std::filesystem::perms::owner_write );
        count++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM