我想在我的计算机上创建一个稀疏文件,该文件适用于 Windows 10 和格式化为 NTFS 的 SSD(固态磁盘)。我尝试了以下由 ChatGPT 生成的代码:
import ctypes
# Define constants for Windows API
FILE_ATTRIBUTE_NORMAL = 0x80
FILE_ATTRIBUTE_SPARSE_FILE = 0x200
FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
def create_sparse_file(file_name, desired_file_size):
handle = ctypes.windll.kernel32.CreateFileW(
file_name,
0x10000000, # GENERIC_WRITE
0,
None,
2, # CREATE_ALWAYS
FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_SPARSE_FILE,
None,
)
if handle == -1:
print("Error creating the file")
else:
# Set the file size to 1GB (size of the sparse file)
ctypes.windll.kernel32.SetFilePointer(handle, desired_file_size, None, 0)
ctypes.windll.kernel32.SetEndOfFile(handle)
# Close the file
ctypes.windll.kernel32.CloseHandle(handle)
# Verify if the file is sparse
result = ctypes.windll.kernel32.DeviceIoControl(
handle,
0x000900C4, # FSCTL_QUERY_ALLOCATED_RANGES
None,
0,
None,
0,
ctypes.byref(ctypes.c_uint64()),
None,
)
if result == 0:
print(f"File '{file_name}' is a sparse file.")
else:
print(f"Failed to create sparse file '{file_name}'")
if __name__ == '__main__':
file_name = r'G:\test.iso'
# Specify the desired file size (in bytes)
desired_file_size = 1024 * 1024 * 1024 # 1 GB
create_sparse_file(file_name, desired_file_size)
目标大小指定为 1 GB。运行上面的代码后,确实生成了一个1GB大小的文件,但是创建的文件的“Size”和“Size on disk”属性都是1GB,这表明该文件实际上并不稀疏。 如何获得真正稀疏的文件?
应用程序必须使用 FSCTL_SET_SPARSE 控制代码显式将文件声明为稀疏文件。
-- https://learn.microsoft.com/en-us/windows/win32/fileio/sparse-file-operations
您无法通过在 dwFlagsAndAttributes 参数中使用 FILE_ATTRIBUTE_SPARSE_FILE 调用 CreateFile 来创建稀疏文件。您必须使用 FSCTL_SET_SPARSE 控制代码。
-- https://learn.microsoft.com/en-us/windows/win32/api/winioctl/ni-winioctl-fsctl_set_sparse