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

CopyFileW

関数
既存ファイルを新しいファイルへコピーする(Unicode版)。
DLLKERNEL32.dll文字セットUnicode (-W)呼出規約winapiSetLastErrorあり対応OSWindows XP 以降

シグネチャ

// KERNEL32.dll  (Unicode / -W)
#include <windows.h>

BOOL CopyFileW(
    LPCWSTR lpExistingFileName,
    LPCWSTR lpNewFileName,
    BOOL bFailIfExists
);

パラメーター

名前型方向説明
lpExistingFileNameLPCWSTRin

既存のファイルの名前。

既定では、名前は MAX_PATH 文字に制限されます。この制限を 32,767 ワイド文字に拡張するには、パスの先頭に "\\?\" を付加します。詳細については、Naming Files, Paths, and Namespaces を参照してください。

ヒント

Windows 10 バージョン 1607 以降では、"\\?\" を付加せずに MAX_PATH の制限を解除するようオプトインできます。詳細については、Naming Files, Paths, and Namespaces の「Maximum Path Length Limitation」セクションを参照してください。

lpExistingFileName が存在しない場合、 CopyFile は失敗し、 GetLastError は ERROR_FILE_NOT_FOUND を返します。

lpNewFileNameLPCWSTRin

新しいファイルの名前。

既定では、名前は MAX_PATH 文字に制限されます。この制限を 32,767 ワイド文字に拡張するには、パスの先頭に "\\?\" を付加します。詳細については、Naming Files, Paths, and Namespaces を参照してください。

ヒント

Windows 10 バージョン 1607 以降では、"\\?\" を付加せずに MAX_PATH の制限を解除するようオプトインできます。詳細については、Naming Files, Paths, and Namespaces の「Maximum Path Length Limitation」セクションを参照してください。

bFailIfExistsBOOLinこのパラメーターが TRUE で、 lpNewFileName で指定された新しいファイルが既に存在する場合、関数は失敗します。このパラメーターが FALSE で、新しいファイルが既に存在する場合、関数は既存のファイルを上書きして 成功します。

戻り値の型: BOOL

公式ドキュメント

CopyFileW (Unicode) 関数 (winbase.h) は、既存のファイルを新しいファイルにコピーします。

戻り値

関数が成功した場合、戻り値は 0 以外の値です。

関数が失敗した場合、戻り値は 0 です。拡張エラー情報を取得するには、 GetLastError を呼び出します。

解説(Remarks)

既存のファイルのセキュリティリソースプロパティ (ATTRIBUTE_SECURITY_INFORMATION) が 新しいファイルにコピーされます。

Windows 7、Windows Server 2008 R2、Windows Server 2008、Windows Vista、Windows Server 2003 および Windows XP: 既存のファイルのセキュリティリソースプロパティは、 Windows 8 および Windows Server 2012 まで新しいファイルにコピーされません。

既存のファイルのファイル属性が新しいファイルにコピーされます。たとえば、既存のファイルに FILE_ATTRIBUTE_READONLY ファイル属性がある場合、 CopyFile の呼び出しによって作成されたコピーにも FILE_ATTRIBUTE_READONLY ファイル属性が設定されます。詳細については、 Retrieving and Changing File Attributes を参照してください。

コピー先のファイルが既に存在し、FILE_ATTRIBUTE_HIDDEN または FILE_ATTRIBUTE_READONLY 属性が設定されている場合、この関数は ERROR_ACCESS_DENIED で失敗します。

CopyFile を使用して暗号化されたファイルをコピーする場合、コピー元ファイルの暗号化に使用された鍵で コピー先ファイルの暗号化を試みます。これができない場合、 この関数は既定の鍵でコピー先ファイルの暗号化を試みます。 これらのいずれの方法も実行できない場合、CopyFile は ERROR_ENCRYPTION_FAILED エラーコードで失敗します。

シンボリックリンクの動作 — コピー元ファイルがシンボリックリンクである場合、実際にコピーされるファイルは そのシンボリックリンクのターゲットです。

コピー先ファイルが既に存在し、シンボリックリンクである場合、そのシンボリックリンクのターゲットが コピー元ファイルによって上書きされます。

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

テクノロジー サポート
Server Message Block (SMB) 3.0 プロトコル はい
SMB 3.0 トランスペアレントフェールオーバー (TFO) はい
SMB 3.0 とスケールアウトファイル共有 (SO) はい
クラスター共有ボリュームファイルシステム (CsvFS) はい
回復性ファイルシステム (ReFS) はい

例

例については、 Retrieving and Changing File Attributes を参照してください。

メモ

winbase.h ヘッダーは、UNICODE プリプロセッサ定数の定義に基づいて、この関数の ANSI 版または Unicode 版を自動的に選択するエイリアスとして CopyFile を定義します。エンコーディング非依存のエイリアスの使用を、エンコーディング非依存でないコードと混在させると、不一致が生じ、コンパイルエラーまたは実行時エラーが発生する可能性があります。詳細については、Conventions for Function Prototypes を参照してください。

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// KERNEL32.dll  (Unicode / -W)
#include <windows.h>

BOOL CopyFileW(
    LPCWSTR lpExistingFileName,
    LPCWSTR lpNewFileName,
    BOOL bFailIfExists
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
static extern bool CopyFileW(
    [MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName,   // LPCWSTR
    [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName,   // LPCWSTR
    bool bFailIfExists   // BOOL
);
<DllImport("KERNEL32.dll", CharSet:=CharSet.Unicode, SetLastError:=True, ExactSpelling:=True)>
Public Shared Function CopyFileW(
    <MarshalAs(UnmanagedType.LPWStr)> lpExistingFileName As String,   ' LPCWSTR
    <MarshalAs(UnmanagedType.LPWStr)> lpNewFileName As String,   ' LPCWSTR
    bFailIfExists As Boolean   ' BOOL
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' lpExistingFileName : LPCWSTR
' lpNewFileName : LPCWSTR
' bFailIfExists : BOOL
Declare PtrSafe Function CopyFileW Lib "kernel32" ( _
    ByVal lpExistingFileName As LongPtr, _
    ByVal lpNewFileName As LongPtr, _
    ByVal bFailIfExists As Long) As Long
' Unicode(W): 文字列は ByVal As LongPtr とし StrPtr(unicodeStr) を渡す
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

CopyFileW = ctypes.windll.kernel32.CopyFileW
CopyFileW.restype = wintypes.BOOL
CopyFileW.argtypes = [
    wintypes.LPCWSTR,  # lpExistingFileName : LPCWSTR
    wintypes.LPCWSTR,  # lpNewFileName : LPCWSTR
    wintypes.BOOL,  # bFailIfExists : BOOL
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('KERNEL32.dll')
CopyFileW = Fiddle::Function.new(
  lib['CopyFileW'],
  [
    Fiddle::TYPE_VOIDP,  # lpExistingFileName : LPCWSTR
    Fiddle::TYPE_VOIDP,  # lpNewFileName : LPCWSTR
    Fiddle::TYPE_INT,  # bFailIfExists : BOOL
  ],
  Fiddle::TYPE_INT)
# Wide strings: pass str.encode("UTF-16LE") + "\x00\x00"
#[link(name = "kernel32")]
extern "system" {
    fn CopyFileW(
        lpExistingFileName: *const u16,  // LPCWSTR
        lpNewFileName: *const u16,  // LPCWSTR
        bFailIfExists: i32  // BOOL
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("KERNEL32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CopyFileW([MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName, [MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName, bool bFailIfExists);
"@
$api = Add-Type -MemberDefinition $sig -Name 'KERNEL32_CopyFileW' -Namespace Win32 -PassThru
# $api::CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
#uselib "KERNEL32.dll"
#func global CopyFileW "CopyFileW" wptr, wptr, wptr
; CopyFileW lpExistingFileName, lpNewFileName, bFailIfExists   ; 戻り値は stat
; lpExistingFileName : LPCWSTR -> "wptr"
; lpNewFileName : LPCWSTR -> "wptr"
; bFailIfExists : BOOL -> "wptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "KERNEL32.dll"
#cfunc global CopyFileW "CopyFileW" wstr, wstr, int
; res = CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
; lpExistingFileName : LPCWSTR -> "wstr"
; lpNewFileName : LPCWSTR -> "wstr"
; bFailIfExists : BOOL -> "int"
; BOOL CopyFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists)
#uselib "KERNEL32.dll"
#cfunc global CopyFileW "CopyFileW" wstr, wstr, int
; res = CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
; lpExistingFileName : LPCWSTR -> "wstr"
; lpNewFileName : LPCWSTR -> "wstr"
; bFailIfExists : BOOL -> "int"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	kernel32 = windows.NewLazySystemDLL("KERNEL32.dll")
	procCopyFileW = kernel32.NewProc("CopyFileW")
)

// lpExistingFileName (LPCWSTR), lpNewFileName (LPCWSTR), bFailIfExists (BOOL)
r1, _, err := procCopyFileW.Call(
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(lpExistingFileName))),
	uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(lpNewFileName))),
	uintptr(bFailIfExists),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function CopyFileW(
  lpExistingFileName: PWideChar;   // LPCWSTR
  lpNewFileName: PWideChar;   // LPCWSTR
  bFailIfExists: BOOL   // BOOL
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'CopyFileW';
result := DllCall("KERNEL32\CopyFileW"
    , "WStr", lpExistingFileName   ; LPCWSTR
    , "WStr", lpNewFileName   ; LPCWSTR
    , "Int", bFailIfExists   ; BOOL
    , "Int")   ; return: BOOL
●CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists) = DLL("KERNEL32.dll", "bool CopyFileW(char*, char*, bool)")
# 呼び出し: CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
# lpExistingFileName : LPCWSTR -> "char*"
# lpNewFileName : LPCWSTR -> "char*"
# bFailIfExists : BOOL -> "bool"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
# ※-W(Unicode)関数。なでしこ1はANSIのため -A 版の利用を推奨。
const std = @import("std");

extern "kernel32" fn CopyFileW(
    lpExistingFileName: [*c]const u16, // LPCWSTR
    lpNewFileName: [*c]const u16, // LPCWSTR
    bFailIfExists: i32 // BOOL
) callconv(std.os.windows.WINAPI) i32;
// Unicode(-W): UTF-16LE のヌル終端バッファ([*c]const u16)を渡す。
proc CopyFileW(
    lpExistingFileName: WideCString,  # LPCWSTR
    lpNewFileName: WideCString,  # LPCWSTR
    bFailIfExists: int32  # BOOL
): int32 {.importc: "CopyFileW", stdcall, dynlib: "KERNEL32.dll".}
# Unicode(-W): WideCString は newWideCString("...") で生成。
pragma(lib, "kernel32");
extern(Windows)
int CopyFileW(
    const(wchar)* lpExistingFileName,   // LPCWSTR
    const(wchar)* lpNewFileName,   // LPCWSTR
    int bFailIfExists   // BOOL
);
ccall((:CopyFileW, "KERNEL32.dll"), stdcall, Int32,
      (Cwstring, Cwstring, Int32),
      lpExistingFileName, lpNewFileName, bFailIfExists)
# lpExistingFileName : LPCWSTR -> Cwstring
# lpNewFileName : LPCWSTR -> Cwstring
# bFailIfExists : BOOL -> Int32
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
# Unicode(-W): Cwstring には transcode(UInt16, "...") 等で UTF-16 を渡す。
local ffi = require("ffi")
ffi.cdef[[
int32_t CopyFileW(
    const uint16_t* lpExistingFileName,
    const uint16_t* lpNewFileName,
    int32_t bFailIfExists);
]]
local kernel32 = ffi.load("kernel32")
-- kernel32.CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
-- lpExistingFileName : LPCWSTR
-- lpNewFileName : LPCWSTR
-- bFailIfExists : BOOL
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
-- Unicode(-W): uint16_t* には UTF-16LE のバッファ(ffi.new("uint16_t[?]", ...))を渡す。
const koffi = require('koffi');
const lib = koffi.load('KERNEL32.dll');
const CopyFileW = lib.func('__stdcall', 'CopyFileW', 'int32_t', ['str16', 'str16', 'int32_t']);
// CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
// lpExistingFileName : LPCWSTR -> 'str16'
// lpNewFileName : LPCWSTR -> 'str16'
// bFailIfExists : BOOL -> 'int32_t'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("KERNEL32.dll", {
  CopyFileW: { parameters: ["buffer", "buffer", "i32"], result: "i32" },
});
// lib.symbols.CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists)
// lpExistingFileName : LPCWSTR -> "buffer"
// lpNewFileName : LPCWSTR -> "buffer"
// bFailIfExists : BOOL -> "i32"
// 文字列は "buffer"。Unicode(-W) は new TextEncoder() ではなく UTF-16LE のバイト列(末尾に \x00\x00)を Uint8Array で渡す。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t CopyFileW(
    const uint16_t* lpExistingFileName,
    const uint16_t* lpNewFileName,
    int32_t bFailIfExists);
C, "KERNEL32.dll");
// $ffi->CopyFileW(lpExistingFileName, lpNewFileName, bFailIfExists);
// lpExistingFileName : LPCWSTR
// lpNewFileName : LPCWSTR
// bFailIfExists : BOOL
// 構造体/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, W32APIOptions.UNICODE_OPTIONS);
    boolean CopyFileW(
        WString lpExistingFileName,   // LPCWSTR
        WString lpNewFileName,   // LPCWSTR
        boolean bFailIfExists   // BOOL
    );
}
// Unicode(-W): WString(入力)/char[](出力)で UTF-16 をマーシャリング。
@[Link("kernel32")]
lib LibKERNEL32
  fun CopyFileW = CopyFileW(
    lpExistingFileName : UInt16*,   # LPCWSTR
    lpNewFileName : UInt16*,   # LPCWSTR
    bFailIfExists : Int32   # BOOL
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef CopyFileWNative = Int32 Function(Pointer<Utf16>, Pointer<Utf16>, Int32);
typedef CopyFileWDart = int Function(Pointer<Utf16>, Pointer<Utf16>, int);
final CopyFileW = DynamicLibrary.open('KERNEL32.dll')
    .lookupFunction<CopyFileWNative, CopyFileWDart>('CopyFileW');
// lpExistingFileName : LPCWSTR -> Pointer<Utf16>
// lpNewFileName : LPCWSTR -> Pointer<Utf16>
// bFailIfExists : BOOL -> Int32
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function CopyFileW(
  lpExistingFileName: PWideChar;   // LPCWSTR
  lpNewFileName: PWideChar;   // LPCWSTR
  bFailIfExists: BOOL   // BOOL
): BOOL; stdcall;
  external 'KERNEL32.dll' name 'CopyFileW';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "CopyFileW"
  c_CopyFileW :: CWString -> CWString -> CInt -> IO CInt
-- lpExistingFileName : LPCWSTR -> CWString
-- lpNewFileName : LPCWSTR -> CWString
-- bFailIfExists : BOOL -> CInt
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let copyfilew =
  foreign "CopyFileW"
    ((ptr uint16_t) @-> (ptr uint16_t) @-> int32_t @-> returning int32_t)
(* lpExistingFileName : LPCWSTR -> (ptr uint16_t) *)
(* lpNewFileName : LPCWSTR -> (ptr uint16_t) *)
(* bFailIfExists : BOOL -> int32_t *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library kernel32 (t "KERNEL32.dll"))
(cffi:use-foreign-library kernel32)

(cffi:defcfun ("CopyFileW" copy-file-w :convention :stdcall) :int32
  (lp-existing-file-name (:string :encoding :utf-16le))   ; LPCWSTR
  (lp-new-file-name (:string :encoding :utf-16le))   ; LPCWSTR
  (b-fail-if-exists :int32))   ; BOOL
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $CopyFileW = Win32::API::More->new('KERNEL32',
    'BOOL CopyFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists)');
# my $ret = $CopyFileW->Call($lpExistingFileName, $lpNewFileName, $bFailIfExists);
# lpExistingFileName : LPCWSTR -> LPCWSTR
# lpNewFileName : LPCWSTR -> LPCWSTR
# bFailIfExists : BOOL -> BOOL
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。
# Unicode(-W): LPCWSTR/LPWSTR は Win32::API が UTF-16 変換を行う。

関連項目

文字セット違い
類似 API
公式の関連項目