Win32 API Reference

Comprehensive documentation for Windows application development

SetFileAttributesA

Function

BOOL SetFileAttributesA(LPCSTR lpFileName, DWORD dwFileAttributes);

The SetFileAttributesA function sets the attributes of a file or a directory.

Parameters

Parameter Description
lpFileName A pointer to a null-terminated string that specifies the name of the file or directory for which to set attributes.

For more information, see "File and Stream I/O Naming Conventions".
dwFileAttributes The file attributes to set for the specified file or directory.

This parameter can be a combination of the following values:
  • FILE_ATTRIBUTE_ARCHIVE (0x00000020)
  • FILE_ATTRIBUTE_COMPRESSED (0x00000800)
  • FILE_ATTRIBUTE_DIRECTORY (0x00000010)
  • FILE_ATTRIBUTE_ENCRYPTED (0x00004000)
  • FILE_ATTRIBUTE_HIDDEN (0x00000002)
  • FILE_ATTRIBUTE_NORMAL (0x00000080)
  • FILE_ATTRIBUTE_OFFLINE (0x00001000)
  • FILE_ATTRIBUTE_READONLY (0x00000001)
  • FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS (0x00400000)
  • FILE_ATTRIBUTE_RECALL_ON_OPEN (0x00000004)
  • FILE_ATTRIBUTE_SYSTEM (0x00000004)
  • FILE_ATTRIBUTE_TEMPORARY (0x00000100)
  • FILE_ATTRIBUTE_UNCOMPRESSED_HINTS (0x00800000)

Return Value

Value Description
TRUE The function succeeded.
FALSE The function failed. To get extended error information, call GetLastError.

Remarks

The SetFileAttributesA function can only set attributes that are not required by the file system. For example, you cannot set the FILE_ATTRIBUTE_DIRECTORY attribute for a file.

To set file attributes, the calling process must have the appropriate access rights. For example, to set the FILE_ATTRIBUTE_READONLY attribute, the process must have write access to the file.

The ANSI version of this function, SetFileAttributesA, is defined in Winbase.h. The Unicode version, SetFileAttributesW, is also defined.

The effective attributes of a file are a combination of the attributes set by this function and the attributes imposed by the file system.

Example

The following example sets the read-only attribute for a file:


#include <windows.h>
#include <stdio.h>

int main() {
    const char* fileName = "my_document.txt";
    DWORD attributes = FILE_ATTRIBUTE_READONLY;

    if (SetFileAttributesA(fileName, attributes)) {
        printf("Successfully set attributes for '%s' to READONLY.\n", fileName);
    } else {
        fprintf(stderr, "Failed to set attributes for '%s'. Error code: %lu\n", fileName, GetLastError());
    }

    return 0;
}
                

Note: Ensure 'my_document.txt' exists and you have write permissions to change its attributes.

Requirements

Attribute Value
Minimum supported client Windows XP
Minimum supported server Windows Server 2003
Target Platform Windows
Header Winbase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll