Wednesday, February 28, 2007

Why can't I unlink a read-only file on Windows?

Every now and then when programming on windows, you run into little quirks, that make you go huh? Then you file the quirk away in your mind and move on.

Today's quirk, which I can't believe I didn't realize a long, long, long time ago. unlink on Windows doesn't remove read-only files.

And the Fix:

Obviously we can't modify unlink to behave like Linux. So if unlink fails we need to remove the read-only attribute from the file to properly remove the file. Here is how to remove the read-only attribute from file programmatically in C++ on Windows:

::SetFileAttributes( "path to readonly file", FILE_ATTRIBUTE_NORMAL);

No comments: