Skip to content

Win32 Set Attributes

A C program that sets a file's attributes to archive plus read-only using SetFileAttributes.

Published Aug 12, 1999

The write half of the attribute pair. SetFileAttributes replaces the entire attribute mask for a file in one call - here setting it to Archive + Readonly (the comment block lists every flag you can combine). Because the call is a full replacement rather than a toggle, the usual pattern is read-modify-write: get the current bits with GetFileAttributes, flip what you need, set the result back. Useful for locking files against accidental edits, marking them for backup, or hiding helper files.

#include <Windows.h>
#include <stdio.h>

/*
FILE_ATTRIBUTE_ARCHIVE
FILE_ATTRIBUTE_COMPRESSED
FILE_ATTRIBUTE_DIRECTORY
FILE_ATTRIBUTE_HIDDEN
FILE_ATTRIBUTE_NORMAL
FILE_ATTRIBUTE_OFFLINE
FILE_ATTRIBUTE_READONLY
FILE_ATTRIBUTE_SYSTEM
FILE_ATTRIBUTE_TEMPORARY
*/

int main(void)
{
    char FileName[128];
    unsigned Attrib;
    sprintf(FileName,"TestFile.Com");

    SetFileAttributes(FileName,FILE_ATTRIBUTE_ARCHIVE+FILE_ATTRIBUTE_READONLY);

    return 0;
}

Check the return value in real code - it fails on nonexistent paths and when you try to clear the Directory bit from an actual directory. For toggling a single bit without clobbering the others:

DWORD a = GetFileAttributes("TestFile.Com");
if (a != INVALID_FILE_ATTRIBUTES)
    SetFileAttributes("TestFile.Com", a & ~FILE_ATTRIBUTE_READONLY); // clear readonly

Pairs directly with the Win32 Get Attributes article above.

An unhandled error has occurred. Reload 🗙