Set file time windows

Set file time windows

Функция SetFileTime устанавливает дату и время, когда файл создавался, последний доступ или последнее изменение.

Синтаксис

Параметры

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

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

[in] Указатель на структуру FILETIME, которая содержит дату и время, когда последний раз файл был доступен. Время последнего обращения включает в себя последний раз, когда файл записывался, читался или, (в случае, если это исполняемый файл) запускался. Этот параметр может быть NULL, еслиприкладная программа не требует установки этой информации.

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

Возвращаемые значения

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

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

Замечания

Не все файловые системы могут фиксировать время создания и последнего доступа и не все файловые системы фиксируют их тем же самым способом. Например, в файловой системе FAT время создания имеет разрешающую способность 10 миллисекунд, время записи имеет разрешающую способность 2 секунд, а время доступа имеет разрешающую способность 1 день (фактически дата доступа). Поэтому, функция GetFileTime не может возвратить тот же самый набор информации о временной характеристике файла, чтобы установить его, используя функцию SetFileTime. NTFS задерживает обновление времени последнего доступа к файлу до одного часа после последнего обращения.

Дополнительную информацию, см. в статье Файловое время .

Если Вы переименовываете или удаляете файл, то восстанавливая его вскоре после этого, Windows находит в кэше информацию о файле, чтобы восстановить. Кэшированная информация включает в себя свою короткую/длинную пару имен и время создания.

SetFileTime function (fileapi.h)

Sets the date and time that the specified file or directory was created, last accessed, or last modified.

Syntax

Parameters

A handle to the file or directory. The handle must have been created using the CreateFile function with the FILE_WRITE_ATTRIBUTES access right. For more information, see File Security and Access Rights.

Читайте также:  Демо версия windows 10 что это

A pointer to a FILETIME structure that contains the new creation date and time for the file or directory. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

A pointer to a FILETIME structure that contains the new last access date and time for the file or directory. The last access time includes the last time the file or directory was written to, read from, or (in the case of executable files) run. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0xFFFFFFFF.

A pointer to a FILETIME structure that contains the new last modified date and time for the file or directory. If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.

To prevent file operations using the given handle from modifying the last access time, call SetFileTime immediately after opening the file handle and pass a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0xFFFFFFFF.

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

Not all file systems can record creation and last access times and not all file systems record them in the same manner. For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). Therefore, the GetFileTime function may not return the same file time information set using SetFileTime. NTFS delays updates to the last access time for a file by up to one hour after the last access.

FILETIME structure (minwinbase.h)

Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

Читайте также:  What file system linux mint

Syntax

Members

The low-order part of the file time.

The high-order part of the file time.

Remarks

To convert a FILETIME structure into a time that is easy to display to a user, use the FileTimeToSystemTime function.

It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times. Instead, you should copy the low- and high-order parts of the file time to a ULARGE_INTEGER structure, perform 64-bit arithmetic on the QuadPart member, and copy the LowPart and HighPart members into the FILETIME structure.

Do not cast a pointer to a FILETIME structure to either a ULARGE_INTEGER* or __int64* value because it can cause alignment faults on 64-bit Windows.

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, the GetFileTime function may not return the same file time information set using the SetFileTime function. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC. For more information, see File Times.

A function using the FILETIME structure can allow for values outside of zero or positive values typically specified by the dwLowDateTime and dwHighDateTime members. For example, the SetFileTime function uses 0xFFFFFFFF to specify that a file’s previous access time should be preserved. For more information, see the topic for the function you are calling.

SetFileTime

This function sets the date and time that a file was created, last accessed, or last modified. A remote application interface (RAPI) version of this function exists, and it is called CeSetFileTime.

Parameters

  • hFile
    [in] Handle to the file for which to set the dates and times. The file handle must have been created with GENERIC_WRITE access to the file.
  • lpCreationTime
    [in] Pointer to a FILETIME structure that contains the date and time the file was created. This parameter can be NULL if the application does not need to set this information.
  • lpLastAccessTime
    [in] Pointer to a FILETIME structure that contains the date and time the file was last accessed. The last access time includes the last time the file was written to, read from, or (in the case of executable files) run. This parameter can be NULL if the application does not need to set this information.
  • lpLastWriteTime
    [in] Pointer to a FILETIME structure that contains the date and time the file was last written to. This parameter can be NULL if the application does not want to set this information.
Читайте также:  Активация windows 10 pro ключики 2019

Return Values

Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError.

Remarks

Not all file systems support all file time parameters. The Windows CE object store stores only one file time and it can be set by any one of the three parameters.

Requirements

Runs on Versions Defined in Include Link to
Windows CE OS 1.0 and later Winbase.h В В

NoteВ В В This API is part of the complete Windows CE OS package as provided by Microsoft. The functionality of a particular platform is determined by the original equipment manufacturer (OEM) and some devices may not support this API.

See Also

В Last updated on Tuesday, July 13, 2004

В© 1992-2000 Microsoft Corporation. All rights reserved.

SWbemDateTime. Сетфилетиме, метод

Метод сетфилетиме объекта SWbemDateTime преобразует дату в строковом формате fileTime в формат даты и времени CIM .

Формат fileTime — это 64-разрядная структура DateTime, представляющая число единиц с 100 до 1 января 1601 г. Инструментарий управления Windows (WMI) (WMI) рассматривает значения fileTime как строковые представления беззнаковых 64-разрядных чисел.

Синтаксис

Параметры

Значение fileTime , используемое для задания объекта.

бислокал [ в необязательное]

Если значение равно true, стрфилетиме интерпретируется как местное время. Свойство времени в формате UTC содержит местное время, преобразованное в правильное смещение в формате UTC. Если бислокал имеет значение false, то стрфилетиме преобразуется непосредственно в значение UTC со смещением 0 (нулем).

Возвращаемое значение

Этот метод не возвращает значение.

Коды ошибок

После завершения метода сетфилетиме объект Err может содержать код ошибки из следующего списка.

вбемерринвалидсинтакс -2147749921 (0x80041021)

Недопустимый формат стрфилетиме .

Комментарии

После успешного вызова сетфилетиме значение DateTime всегда интерпретируется как абсолютное значение (DateTime) , а параметру IsFalse — значение false.

Примеры

Примеры использования объекта SWbemDateTime для преобразования значений DateTime CIM в формат fileTime или в формат _ даты VT см. в разделе задачи WMI: даты и время. Описание формата DateTime в CIM см. в разделе Формат даты и времени.

Оцените статью