Windows set file attributes

Функция SetFileAttributes

Функция SetFileAttributes устанавливает атрибуты файла.

[in] Указатель на строку символов, определяющую имя файла, атрибуты которого должны быть установлены.

Windows NT/2000/XP: В версии ANSI этой функции, имя ограничивается значением флажка MAX_PATH . Чтобы выйти за пределы этого ограничения, до длины 32 767 символов, вызовите Unicode версию этой функции и присоедините спереди пути «\\?\«. Подробную информацию см. в статье Именование файлов .

Windows 95/98/Me: Эта символьная строка не должна выходить за пределы значения флажка MAX_PATH .

[in] Устанавливаемые атрибуты файла. Этот параметр может состоять из одного или нескольких нижеследующих значений. Однако, все другие значения отменяют атрибут FILE_ATTRIBUTE_NORMAL .

Атрибут Предназначение
FILE_ATTRIBUTE_ARCHIVE Этот файл — архивный файл. Приложения используют этот атрибут, чтобы отметить файлы для резервирования или перемещения.
FILE_ATTRIBUTE_HIDDEN Файл скрытый. Он не включается в обычный список каталога.
FILE_ATTRIBUTE_NORMAL У файла нет другого набора атрибутов. Этот атрибут допустим только в том случае, если используется в одиночку.
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED Файл не индексируется содержащей индексацию службой.
FILE_ATTRIBUTE_OFFLINE Данные файла непосредственно не доступны. Этот атрибут указывает, что данные файла были физически перемещены на автономное запоминающее устройство. Этот атрибут используется Удаленным хранилищем, программным обеспечением иерархического управления памятью. Приложения не должны произвольно изменять этот атрибут.
FILE_ATTRIBUTE_READONLY Файл только для чтения. Приложения могут читать файл, но не могут записать в него или удалить его.
FILE_ATTRIBUTE_SYSTEM Файл — это часть операционной системы или используется исключительно ею.
FILE_ATTRIBUTE_TEMPORARY Файл используется для временного сохранения. Файловые системы избегают писать данные обратно на запоминающее устройство большой емкости, если доступна достаточная кэш-память, потому что приложение часто удаляет временный файл вскоре после того, как дескриптор закрывается. В этом случае, система может полностью отменить запись данных. В противном случае, данные должны быть записаны после того, как дескриптор закроется.

Если функция завершается успешно, возвращаемое значение — не нуль.

Если функция завершается ошибкой, величина возвращаемого значения — нуль. Чтобы получить дополнительные данные об ошибке, вызовите GetLastError .

Нижеследующая таблица описывает, как установить атрибуты, которые не могут быть установлены при помощи использования функции SetFileAttributes.

Атрибут Как установить его
FILE_ATTRIBUTE_COMPRESSED Чтобы установить сжатое состояние файла, используйте функцию DeviceIoControl с операцией FSCTL_SET_COMPRESSION .
FILE_ATTRIBUTE_DEVICE Зарезервировано; не используется.
FILE_ATTRIBUTE_DIRECTORY Файлы не могут быть преобразованы в каталоги. Чтобы создать каталог, используйте функцию CreateDirectory или CreateDirectoryEx .
FILE_ATTRIBUTE_ENCRYPTED Чтобы создать зашифрованный файл, используйте функцию CreateFile с атрибутом FILE_ATTRIBUTE_ENCRYPTED . Чтобы конвертировать существующий файл в зашифрованный, используйте функцию EncryptFile .
FILE_ATTRIBUTE_REPARSE_POINT Чтобы связать точку монтирования с файлом или каталогом, используйте функцию DeviceIoControl с операцией FSCTL_SET_REPARSE_POINT.
FILE_ATTRIBUTE_SPARSE_FILE Чтобы установить атрибут разреженности файла, используйте функцию DeviceIoControl с операцией FSCTL_SET_SPARSE .
Читайте также:  Не запускается postgresql windows после аварийного завершения

Размещение и совместимость SetFileAttributes

Windows set file attributes

Как изменить атрибуты файла на C++. У каждого файла в ОС Windows есть аттрибуты. A H R S.

  • Архивный (A)
  • Скрытый (H)
  • Только чтение (R)
  • Системный (S)

Изменить эти параметры можно и вручную, но некоторые из них сложно сменить без особых навыков работы в ОС. ДА и не всегда это нужно делать вручную. В WinAPI от Билла есть функция SetFileAttributes.

Функция SetFileAttributes — устанавливает атрибуты файла.

BOOL SetFileAttributes(
LPCTSTR lpFileName, // имя файла
DWORD dwFileAttributes // атрибуты
);

lpFileName —Указатель на строку символов, определяющую имя файла, атрибуты которого должны быть установлены.

Windows NT/2000/XP: В версии ANSI этой функции, имя ограничивается значением флажка MAX_PATH. Чтобы выйти за пределы этого ограничения, до длины 32 767 символов, вызовите Unicode версию этой функции и присоедините спереди пути «\\?\». Подробную информацию см. в статье Именование файлов.

Windows 95/98/Me: Эта символьная строка не должна выходить за пределы значения флажка MAX_PATH.

dwFileAttributes — Устанавливаемые атрибуты файла. Этот параметр может состоять из одного или нескольких нижеследующих значений. Однако, все другие значения отменяют атрибут FILE_ATTRIBUTE_NORMAL.

FILE_ATTRIBUTE_ARCHIVE Этот файл — архивный файл. Приложения используют этот атрибут, чтобы отметить файлы для резервирования или перемещения.
FILE_ATTRIBUTE_HIDDEN Файл скрытый. Он не включается в обычный список каталога.
FILE_ATTRIBUTE_NORMAL У файла нет другого набора атрибутов. Этот атрибут допустим только в том случае, если используется в одиночку.
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED Файл не индексируется содержащей индексацию службой.
FILE_ATTRIBUTE_OFFLINE Данные файла непосредственно не доступны. Этот атрибут указывает, что данные файла были физически перемещены на автономное запоминающее устройство. Этот атрибут используется Удаленным хранилищем, программным обеспечением иерархического управления памятью. Приложения не должны произвольно изменять этот атрибут.
FILE_ATTRIBUTE_READONLY Файл только для чтения. Приложения могут читать файл, но не могут записать в него или удалить его.
FILE_ATTRIBUTE_SYSTEM Файл — это часть операционной системы или используется исключительно ею.
FILE_ATTRIBUTE_TEMPORARY Файл используется для временного сохранения. Файловые системы избегают писать данные обратно на запоминающее устройство большой емкости, если доступна достаточная кэш-память, потому что приложение часто удаляет временный файл вскоре после того, как дескриптор закрывается. В этом случае, система может полностью отменить запись данных. В противном случае, данные должны быть записаны после того, как дескриптор закроется.

Если функция завершается успешно, возвращаемое значение — не нуль.

Если функция завершается ошибкой, величина возвращаемого значения — нуль. Чтобы получить дополнительные данные об ошибке, вызовите GetLastError.

#include
SetFileAttributes(«1.exe»,FILE_ATTRIBUTE_HIDDEN);

SetFileAttributesTransactedA function (winbase.h)

[Microsoft strongly recommends developers utilize alternative means to achieve your application’s needs. Many scenarios that TxF was developed for can be achieved through simpler and more readily available techniques. Furthermore, TxF may not be available in future versions of Microsoft Windows. For more information, and alternatives to TxF, please see Alternatives to using Transactional NTFS.]

Читайте также:  Poky linux ��� ���

Sets the attributes for a file or directory as a transacted operation.

Syntax

Parameters

The name of the file whose attributes are to be set.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend «\?» to the path. For more information, see File Names, Paths, and Namespaces.

The file must reside on the local computer; otherwise, the function fails and the last error code is set to ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE.

The file attributes to set for the file.

For a list of file attribute value and their descriptions, see File Attribute Constants. This parameter can be one or more values, combined using the bitwise-OR operator. However, all other values override FILE_ATTRIBUTE_NORMAL.

Not all attributes are supported by this function. For more information, see the Remarks section.

The following is a list of supported attribute values.

FILE_ATTRIBUTE_ARCHIVE (32 (0x20))

FILE_ATTRIBUTE_HIDDEN (2 (0x2))

FILE_ATTRIBUTE_NORMAL (128 (0x80))

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED (8192 (0x2000))

FILE_ATTRIBUTE_OFFLINE (4096 (0x1000))

FILE_ATTRIBUTE_READONLY (1 (0x1))

FILE_ATTRIBUTE_SYSTEM (4 (0x4))

FILE_ATTRIBUTE_TEMPORARY (256 (0x100))

A handle to the transaction. This handle is returned by the CreateTransaction function.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The following table describes how to set the attributes that cannot be set using SetFileAttributesTransacted. Note that these are not transacted operations.

Attribute How to Set
FILE_ATTRIBUTE_COMPRESSED

To set a file’s compression state, use the DeviceIoControl function with the FSCTL_SET_COMPRESSION operation.
FILE_ATTRIBUTE_DEVICE

Reserved; do not use.
FILE_ATTRIBUTE_DIRECTORY

Files cannot be converted into directories. To create a directory, use the CreateDirectory or CreateDirectoryEx function.
FILE_ATTRIBUTE_ENCRYPTED

To create an encrypted file, use the CreateFile function with the FILE_ATTRIBUTE_ENCRYPTED attribute. To convert an existing file into an encrypted file, use the EncryptFile function.
FILE_ATTRIBUTE_REPARSE_POINT

To associate a reparse point with a file or directory, use the DeviceIoControl function with the FSCTL_SET_REPARSE_POINT operation.
FILE_ATTRIBUTE_SPARSE_FILE

To set a file’s sparse attribute, use the DeviceIoControl function with the FSCTL_SET_SPARSE operation.

В

If a file is open for modification in a transaction, no other thread can successfully open the file for modification until the transaction is committed. If a transacted thread opens the file first, any subsequent threads that attempt to open the file for modification before the transaction is committed will receive a sharing violation. If a non-transacted thread opens the file for modification before the transacted thread does, and it is still open when the transacted thread attempts to open it, the transaction will receive the ERROR_TRANSACTIONAL_CONFLICT error.

For more information on transactions, see Transactional NTFS.

In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.

Technology Supported
Server Message Block (SMB) 3.0 protocol No
SMB 3.0 Transparent Failover (TFO) No
SMB 3.0 with Scale-out File Shares (SO) No
Cluster Shared Volume File System (CsvFS) No
Resilient File System (ReFS) No

В

SMB 3.0 does not support TxF.

Transacted Operations

The winbase.h header defines SetFileAttributesTransacted as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

File. Set Attributes(String, FileAttributes) Method

Definition

Sets the specified FileAttributes of the file on the specified path.

Parameters

The path to the file.

A bitwise combination of the enumeration values.

Exceptions

path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.

The specified path, file name, or both exceed the system-defined maximum length.

path is in an invalid format.

The specified path is invalid, (for example, it is on an unmapped drive).

The file cannot be found.

path specified a file that is read-only.

This operation is not supported on the current platform.

path specified a directory.

The caller does not have the required permission.

Examples

The following example demonstrates the GetAttributes and SetAttributes methods by applying the Archive and Hidden attributes to a file.

Remarks

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

Certain file attributes, such as Hidden and ReadOnly, can be combined. Other attributes, such as Normal, must be used alone.

It is not possible to change the compression status of a File object using the SetAttributes method.

For a list of common I/O tasks, see Common I/O Tasks.

Читайте также:  Start screen windows 10 что это
Оцените статью