python 3 creating hard links on ntfs

eryk sun eryksun at gmail.com
Wed Apr 18 20:37:10 EDT 2018


On Wed, Apr 18, 2018 at 8:06 PM,  <zljubisic at gmail.com> wrote:
> Is it possible to create hard links on windows with ntfs?
> On linux I can use os.link, but how about windows?

Windows support was added for os.link years ago in version 3.2.
Internally it's implemented via WinAPI CreateHardLink, which in turn
calls NTAPI NtSetInformationFile to to set the FileLinkInformation.
The only Microsoft filesystem that implements hard links is NTFS, and
it's implemented for files only, not directories. Non-Microsoft
file-system drivers may also implement it, e.g. a driver that allows
mounting ext2 or ext3 filesystems.

Percival linked an old topic that has ctypes code to call
CreateHardLinkA. Do not use that code. It's dangerously sloppy
crash-bait and unreliable with how Python 2 ctypes creates the call
stack for 64-bit Windows. Do imports, DLL loading, type definitions,
and function prototyping (i.e. errcheck, restype, argtypes) one time
only, at module or class scope. Use `kernel32 = WinDLL('kernel32',
use_last_error=True)` instead of windll.kernel32. Use Windows typedefs
from the ctypes.wintypes module. Use None for a NULL pointer, not 0.
If a WinAPI function fails, use ctypes.get_last_error() to get the
error code, and raise a useful exception via `raise
ctypes.WinError(error_code)`. Always use Unicode, especially for
file-system functions, e.g. call CreateHardlinkW, not CreateHardLinkA.
The [A]NSI function wrappers were added in the 1990s for compatibility
with Windows 9x systems, which didn't have Unicode support. That era
is ancient history.



More information about the Python-list mailing list