Win32 API 日本語リファレンス
ホームStorage.FileSystem › SetFileInformationByHandle

SetFileInformationByHandle

関数
ハンドルでファイルの各種情報を変更する。
DLLKERNEL32.dll呼出規約winapiSetLastErrorあり対応OSWindows Vista 以降

シグネチャ

// KERNEL32.dll
#include <windows.h>

BOOL SetFileInformationByHandle(
    HANDLE hFile,
    FILE_INFO_BY_HANDLE_CLASS FileInformationClass,
    void* lpFileInformation,
    DWORD dwBufferSize
);

パラメーター

名前方向説明
hFileHANDLEin

情報を変更する対象のファイルへのハンドルです。

このハンドルは、要求する変更に適した権限で開かれている必要があります。詳細については、 「解説」および「サンプルコード」のセクションを参照してください。

このハンドルはパイプハンドルであってはなりません。

FileInformationClassFILE_INFO_BY_HANDLE_CLASSin

変更する情報の種類を指定する FILE_INFO_BY_HANDLE_CLASS 列挙体の 値です。

有効な値の一覧については、「解説」のセクションを参照してください。

lpFileInformationvoid*in

指定したファイル情報クラスに対して変更する情報を格納したバッファへのポインターです。 このパラメーターが指す構造体は、FileInformationClass で指定したクラスに対応します。

有効な構造体の種類の一覧については、「解説」のセクションを参照してください。

dwBufferSizeDWORDinlpFileInformation のサイズ(バイト単位)です。

戻り値の型: BOOL

公式ドキュメント

指定したファイルのファイル情報を設定します。

戻り値

成功した場合は 0 以外の値を返し、それ以外の場合は 0 を返します。

拡張エラー情報を取得するには、 GetLastError を呼び出します。

解説(Remarks)

一部のファイル情報クラスは、オペレーティングシステムのリリースによって動作がわずかに異なります。これらの クラスは基盤となるドライバーによってサポートされており、返される情報はオペレーティングシステムのリリース間で 変更される可能性があります。

次の表は、この関数で使用できる有効なファイル情報クラスと、それに対応するデータ構造体の種類を示しています。

FileInformationClass の値 lpFileInformation の型
FileBasicInfo

0

FILE_BASIC_INFO

FileRenameInfo

3

FILE_RENAME_INFO

FileDispositionInfo

4

FILE_DISPOSITION_INFO

FileAllocationInfo

5

FILE_ALLOCATION_INFO

FileEndOfFileInfo

6

FILE_END_OF_FILE_INFO

FileIoPriorityHintInfo

12

FILE_IO_PRIORITY_HINT_INFO

SetFileInformationByHandle で使用するファイルハンドルを作成する際には、適切なアクセスフラグを 指定する必要があります。たとえば、アプリケーションが DeleteFile メンバーを TRUE に設定した FILE_DISPOSITION_INFO を使用している場合、 そのファイルには CreateFile 関数の呼び出しで DELETE アクセスを要求しておく必要があります。この例については、「サンプルコード」のセクションを 参照してください。ファイルのアクセス許可の詳細については、 File Security and Access Rights を参照してください。

ハンドルにトランザクションが関連付けられている場合、情報クラス FileBasicInfoFileRenameInfoFileAllocationInfoFileEndOfFileInfoFileDispositionInfo に対する変更はトランザクション 処理されます。FileDispositionInfo を指定した場合、DeleteFile 操作が要求されたときに削除操作のみがトランザクション処理されます。この場合、ハンドルを閉じる前に トランザクションがコミットされなければ、削除は行われません。TxF の詳細については、 Transactional NTFS (TxF) を参照してください。

Windows 8 および Windows Server 2012 では、この関数は次のテクノロジーでサポートされています。

テクノロジー サポート
Server Message Block (SMB) 3.0 プロトコル はい
SMB 3.0 Transparent Failover (TFO) コメントを参照
SMB 3.0 with Scale-out File Shares (SO) コメントを参照
Cluster Shared Volume File System (CsvFS) はい
Resilient File System (ReFS) はい

SMB 3.0 は、継続的可用性機能を持つファイル共有上での代替データストリームの名前変更をサポートしません。

次の C++ の例は、ファイルを作成し、ハンドルが閉じられたときに削除されるようにマークする方法を示しています。

//...
  HANDLE hFile = CreateFile( TEXT("tempfile"), 
                             GENERIC_READ | GENERIC_WRITE | DELETE,
                             0 /* exclusive access */,
                             NULL, 
                             CREATE_ALWAYS,
                             0, 
                             NULL);

  if (hFile != INVALID_HANDLE_VALUE)
   {
    FILE_DISPOSITION_INFO fdi;
    fdi.DeleteFile = TRUE; // marking for deletion

    BOOL fResult = SetFileInformationByHandle( hFile, 
                                               FileDispositionInfo, 
                                               &fdi, 
                                               sizeof(FILE_DISPOSITION_INFO) );

    if (fResult)
     {
      // File will be deleted upon CloseHandle.
      _tprintf( TEXT("SetFileInformationByHandle marked tempfile for deletion\n") );

      // ... 
      // Now use the file for whatever temp data storage you need,
      // it will automatically be deleted upon CloseHandle or 
      // application termination.
      // ...
     }
    else
     {
      _tprintf( TEXT("error %lu:  SetFileInformationByHandle could not mark tempfile for deletion\n"), 
                GetLastError() );
     }

    CloseHandle(hFile); 

    // At this point, the file is closed and deleted by the system.
   }
  else 
   {
    _tprintf( TEXT("error %lu:  could not create tempfile\n"), 
              GetLastError() );
 }
//...
出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// KERNEL32.dll
#include <windows.h>

BOOL SetFileInformationByHandle(
    HANDLE hFile,
    FILE_INFO_BY_HANDLE_CLASS FileInformationClass,
    void* lpFileInformation,
    DWORD dwBufferSize
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool SetFileInformationByHandle(
    IntPtr hFile,   // HANDLE
    int FileInformationClass,   // FILE_INFO_BY_HANDLE_CLASS
    IntPtr lpFileInformation,   // void*
    uint dwBufferSize   // DWORD
);
<DllImport("KERNEL32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function SetFileInformationByHandle(
    hFile As IntPtr,   ' HANDLE
    FileInformationClass As Integer,   ' FILE_INFO_BY_HANDLE_CLASS
    lpFileInformation As IntPtr,   ' void*
    dwBufferSize As UInteger   ' DWORD
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' hFile : HANDLE
' FileInformationClass : FILE_INFO_BY_HANDLE_CLASS
' lpFileInformation : void*
' dwBufferSize : DWORD
Declare PtrSafe Function SetFileInformationByHandle Lib "kernel32" ( _
    ByVal hFile As LongPtr, _
    ByVal FileInformationClass As Long, _
    ByVal lpFileInformation As LongPtr, _
    ByVal dwBufferSize As Long) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

SetFileInformationByHandle = ctypes.windll.kernel32.SetFileInformationByHandle
SetFileInformationByHandle.restype = wintypes.BOOL
SetFileInformationByHandle.argtypes = [
    wintypes.HANDLE,  # hFile : HANDLE
    ctypes.c_int,  # FileInformationClass : FILE_INFO_BY_HANDLE_CLASS
    ctypes.POINTER(None),  # lpFileInformation : void*
    wintypes.DWORD,  # dwBufferSize : DWORD
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('KERNEL32.dll')
SetFileInformationByHandle = Fiddle::Function.new(
  lib['SetFileInformationByHandle'],
  [
    Fiddle::TYPE_VOIDP,  # hFile : HANDLE
    Fiddle::TYPE_INT,  # FileInformationClass : FILE_INFO_BY_HANDLE_CLASS
    Fiddle::TYPE_VOIDP,  # lpFileInformation : void*
    -Fiddle::TYPE_INT,  # dwBufferSize : DWORD
  ],
  Fiddle::TYPE_INT)
#[link(name = "kernel32")]
extern "system" {
    fn SetFileInformationByHandle(
        hFile: *mut core::ffi::c_void,  // HANDLE
        FileInformationClass: i32,  // FILE_INFO_BY_HANDLE_CLASS
        lpFileInformation: *mut (),  // void*
        dwBufferSize: u32  // DWORD
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", SetLastError = true)]
public static extern bool SetFileInformationByHandle(IntPtr hFile, int FileInformationClass, IntPtr lpFileInformation, uint dwBufferSize);
"@
$api = Add-Type -MemberDefinition $sig -Name 'KERNEL32_SetFileInformationByHandle' -Namespace Win32 -PassThru
# $api::SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
#uselib "KERNEL32.dll"
#func global SetFileInformationByHandle "SetFileInformationByHandle" sptr, sptr, sptr, sptr
; SetFileInformationByHandle hFile, FileInformationClass, lpFileInformation, dwBufferSize   ; 戻り値は stat
; hFile : HANDLE -> "sptr"
; FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> "sptr"
; lpFileInformation : void* -> "sptr"
; dwBufferSize : DWORD -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "KERNEL32.dll"
#cfunc global SetFileInformationByHandle "SetFileInformationByHandle" sptr, int, sptr, int
; res = SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
; hFile : HANDLE -> "sptr"
; FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> "int"
; lpFileInformation : void* -> "sptr"
; dwBufferSize : DWORD -> "int"
; BOOL SetFileInformationByHandle(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, void* lpFileInformation, DWORD dwBufferSize)
#uselib "KERNEL32.dll"
#cfunc global SetFileInformationByHandle "SetFileInformationByHandle" intptr, int, intptr, int
; res = SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
; hFile : HANDLE -> "intptr"
; FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> "int"
; lpFileInformation : void* -> "intptr"
; dwBufferSize : DWORD -> "int"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	kernel32 = windows.NewLazySystemDLL("KERNEL32.dll")
	procSetFileInformationByHandle = kernel32.NewProc("SetFileInformationByHandle")
)

// hFile (HANDLE), FileInformationClass (FILE_INFO_BY_HANDLE_CLASS), lpFileInformation (void*), dwBufferSize (DWORD)
r1, _, err := procSetFileInformationByHandle.Call(
	uintptr(hFile),
	uintptr(FileInformationClass),
	uintptr(lpFileInformation),
	uintptr(dwBufferSize),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function SetFileInformationByHandle(
  hFile: THandle;   // HANDLE
  FileInformationClass: Integer;   // FILE_INFO_BY_HANDLE_CLASS
  lpFileInformation: Pointer;   // void*
  dwBufferSize: DWORD   // DWORD
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'SetFileInformationByHandle';
result := DllCall("KERNEL32\SetFileInformationByHandle"
    , "Ptr", hFile   ; HANDLE
    , "Int", FileInformationClass   ; FILE_INFO_BY_HANDLE_CLASS
    , "Ptr", lpFileInformation   ; void*
    , "UInt", dwBufferSize   ; DWORD
    , "Int")   ; return: BOOL
●SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize) = DLL("KERNEL32.dll", "bool SetFileInformationByHandle(void*, int, void*, dword)")
# 呼び出し: SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
# hFile : HANDLE -> "void*"
# FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> "int"
# lpFileInformation : void* -> "void*"
# dwBufferSize : DWORD -> "dword"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "kernel32" fn SetFileInformationByHandle(
    hFile: ?*anyopaque, // HANDLE
    FileInformationClass: i32, // FILE_INFO_BY_HANDLE_CLASS
    lpFileInformation: ?*anyopaque, // void*
    dwBufferSize: u32 // DWORD
) callconv(std.os.windows.WINAPI) i32;
proc SetFileInformationByHandle(
    hFile: pointer,  # HANDLE
    FileInformationClass: int32,  # FILE_INFO_BY_HANDLE_CLASS
    lpFileInformation: pointer,  # void*
    dwBufferSize: uint32  # DWORD
): int32 {.importc: "SetFileInformationByHandle", stdcall, dynlib: "KERNEL32.dll".}
pragma(lib, "kernel32");
extern(Windows)
int SetFileInformationByHandle(
    void* hFile,   // HANDLE
    int FileInformationClass,   // FILE_INFO_BY_HANDLE_CLASS
    void* lpFileInformation,   // void*
    uint dwBufferSize   // DWORD
);
ccall((:SetFileInformationByHandle, "KERNEL32.dll"), stdcall, Int32,
      (Ptr{Cvoid}, Int32, Ptr{Cvoid}, UInt32),
      hFile, FileInformationClass, lpFileInformation, dwBufferSize)
# hFile : HANDLE -> Ptr{Cvoid}
# FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> Int32
# lpFileInformation : void* -> Ptr{Cvoid}
# dwBufferSize : DWORD -> UInt32
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
int32_t SetFileInformationByHandle(
    void* hFile,
    int32_t FileInformationClass,
    void* lpFileInformation,
    uint32_t dwBufferSize);
]]
local kernel32 = ffi.load("kernel32")
-- kernel32.SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
-- hFile : HANDLE
-- FileInformationClass : FILE_INFO_BY_HANDLE_CLASS
-- lpFileInformation : void*
-- dwBufferSize : DWORD
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('KERNEL32.dll');
const SetFileInformationByHandle = lib.func('__stdcall', 'SetFileInformationByHandle', 'int32_t', ['void *', 'int32_t', 'void *', 'uint32_t']);
// SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
// hFile : HANDLE -> 'void *'
// FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> 'int32_t'
// lpFileInformation : void* -> 'void *'
// dwBufferSize : DWORD -> 'uint32_t'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("KERNEL32.dll", {
  SetFileInformationByHandle: { parameters: ["pointer", "i32", "pointer", "u32"], result: "i32" },
});
// lib.symbols.SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize)
// hFile : HANDLE -> "pointer"
// FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> "i32"
// lpFileInformation : void* -> "pointer"
// dwBufferSize : DWORD -> "u32"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t SetFileInformationByHandle(
    void* hFile,
    int32_t FileInformationClass,
    void* lpFileInformation,
    uint32_t dwBufferSize);
C, "KERNEL32.dll");
// $ffi->SetFileInformationByHandle(hFile, FileInformationClass, lpFileInformation, dwBufferSize);
// hFile : HANDLE
// FileInformationClass : FILE_INFO_BY_HANDLE_CLASS
// lpFileInformation : void*
// dwBufferSize : DWORD
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Kernel32 extends StdCallLibrary {
    Kernel32 INSTANCE = Native.load("kernel32", Kernel32.class);
    boolean SetFileInformationByHandle(
        Pointer hFile,   // HANDLE
        int FileInformationClass,   // FILE_INFO_BY_HANDLE_CLASS
        Pointer lpFileInformation,   // void*
        int dwBufferSize   // DWORD
    );
}
@[Link("kernel32")]
lib LibKERNEL32
  fun SetFileInformationByHandle = SetFileInformationByHandle(
    hFile : Void*,   # HANDLE
    FileInformationClass : Int32,   # FILE_INFO_BY_HANDLE_CLASS
    lpFileInformation : Void*,   # void*
    dwBufferSize : UInt32   # DWORD
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef SetFileInformationByHandleNative = Int32 Function(Pointer<Void>, Int32, Pointer<Void>, Uint32);
typedef SetFileInformationByHandleDart = int Function(Pointer<Void>, int, Pointer<Void>, int);
final SetFileInformationByHandle = DynamicLibrary.open('KERNEL32.dll')
    .lookupFunction<SetFileInformationByHandleNative, SetFileInformationByHandleDart>('SetFileInformationByHandle');
// hFile : HANDLE -> Pointer<Void>
// FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> Int32
// lpFileInformation : void* -> Pointer<Void>
// dwBufferSize : DWORD -> Uint32
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function SetFileInformationByHandle(
  hFile: THandle;   // HANDLE
  FileInformationClass: Integer;   // FILE_INFO_BY_HANDLE_CLASS
  lpFileInformation: Pointer;   // void*
  dwBufferSize: DWORD   // DWORD
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'SetFileInformationByHandle';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "SetFileInformationByHandle"
  c_SetFileInformationByHandle :: Ptr () -> Int32 -> Ptr () -> Word32 -> IO CInt
-- hFile : HANDLE -> Ptr ()
-- FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> Int32
-- lpFileInformation : void* -> Ptr ()
-- dwBufferSize : DWORD -> Word32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let setfileinformationbyhandle =
  foreign "SetFileInformationByHandle"
    ((ptr void) @-> int32_t @-> (ptr void) @-> uint32_t @-> returning int32_t)
(* hFile : HANDLE -> (ptr void) *)
(* FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> int32_t *)
(* lpFileInformation : void* -> (ptr void) *)
(* dwBufferSize : DWORD -> uint32_t *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library kernel32 (t "KERNEL32.dll"))
(cffi:use-foreign-library kernel32)

(cffi:defcfun ("SetFileInformationByHandle" set-file-information-by-handle :convention :stdcall) :int32
  (h-file :pointer)   ; HANDLE
  (file-information-class :int32)   ; FILE_INFO_BY_HANDLE_CLASS
  (lp-file-information :pointer)   ; void*
  (dw-buffer-size :uint32))   ; DWORD
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $SetFileInformationByHandle = Win32::API::More->new('KERNEL32',
    'BOOL SetFileInformationByHandle(HANDLE hFile, int FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize)');
# my $ret = $SetFileInformationByHandle->Call($hFile, $FileInformationClass, $lpFileInformation, $dwBufferSize);
# hFile : HANDLE -> HANDLE
# FileInformationClass : FILE_INFO_BY_HANDLE_CLASS -> int
# lpFileInformation : void* -> LPVOID
# dwBufferSize : DWORD -> DWORD
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

公式の関連項目
使用する型