CreateFile函数详解

来源:互联网 发布:公司商标制作软件 编辑:程序博客网 时间:2024/05/17 16:56

CreateFile函数详解

CreateFile

CreateFile 函数创建或打开下列对象,并返回一个可以用来访问这些对象的句柄。

例如:
 
文件 files
 
管道pipes
 
邮槽 mailslots
 
通信资源 communications resources
 
磁盘驱动器(仅适用于 windowsNT disk devices(Windows NT only)
 
控制台 consoles
 
文件夹(仅用于打开) directories(open only)

HANDLE CreateFile(
 LPCTSTR lpFileName,    //
指向文件名的指针
 DWORD dwDesiredAccess,    //
访问模式(写 / 读)
 DWORD dwShareMode,    //
共享模式
 LPSECURITY_ATTRIBUTES lpSecurityAttributes, //
指向安全属性的指针
 DWORD dwCreationDisposition,   //
如何创建
 DWORD dwFlagsAndAttributes,   //
文件属性
 HANDLE hTemplateFile    //
用于复制文件句柄
);

Parametes
参数列表

参数

类型及说明

lpFileName

String ,要打开的文件的名字

dwDesiredAccess

Long ,如果为 GENERIC_READ 表示允许对设备进行读访问;如果为 GENERIC_WRITE 表示允许对设备进行写访问(可组合使用);如果为零,表示只允许获取与一个设备有关的信息

dwShareMode

Long 零表示不共享,其它程序不能再打开这个对象,否则出错,只能等到释放后才能打开; FILE_SHARE_READ FILE_SHARE_WRITE 表示允许对文件进行共享访问

lpSecurityAttributes

SECURITY_ATTRIBUTES ,指向一个 SECURITY_ATTRIBUTES 结构的指针,定义了文件的安全特性(如果操作系统支持的话)

dwCreationDisposition

Long ,下述常数之一

CREATE_NEW

创建文件;如文件存在则会出错

CREATE_ALWAYS

创建文件,会改写前一个文件

OPEN_EXISTING

文件必须已经存在。由设备提出要求

OPEN_ALWAYS

如文件不存在则创建它

TRUNCATE_EXISTING

讲现有文件缩短为零长度

dwFlagsAndAttributes

Long ,一个或多个下述常数

FILE_ATTRIBUTE_ARCHIVE

标记归档属性

FILE_ATTRIBUTE_COMPRESSED

将文件标记为已压缩,或者标记为文件在目录中的默认压缩方式

FILE_ATTRIBUTE_NORMAL

默认属性

FILE_ATTRIBUTE_HIDDEN

隐藏文件或目录

FILE_ATTRIBUTE_READONLY

文件为只读

FILE_ATTRIBUTE_SYSTEM

文件为系统文件

FILE_FLAG_WRITE_THROUGH

操作系统不得推迟对文件的写操作

FILE_FLAG_OVERLAPPED

允许对文件进行重叠操作

FILE_FLAG_NO_BUFFERING

禁止对文件进行缓冲处理。文件只能写入磁盘卷的扇区块

FILE_FLAG_RANDOM_ACCESS

针对随机访问对文件缓冲进行优化

FILE_FLAG_SEQUENTIAL_SCAN

针对连续访问对文件缓冲进行优化

FILE_FLAG_DELETE_ON_CLOSE

关闭了上一次打开的句柄后,将文件删除。特别适合临时文件

也可在 Windows NT 下组合使用下述常数标记:

SECURITY_ANONYMOUS SECURITY_IDENTIFICATION SECURITY_IMPERSONATION SECURITY_DELEGATION SECURITY_CONTEXT_TRACKING SECURITY_EFFECTIVE_ONLY

hTemplateFile

Long ,如果不为零,则指定一个文件句柄。新文件将从这个文件中复制扩展属性

返回值

如执行成功,则返回文件句柄。 INVALID_HANDLE_VALUE 表示出错,会设置 GetLastError 。即使函数成功,但若文件存在,且指定了 CREATE_ALWAYS OPEN_ALWAYS GetLastError 也会设为 ERROR_ALREADY_EXISTS

lpFileName
 Pointer to a null-terminated string that specifies the name of the object(file, pipe, mailslot, communications resource, disk device, console, or directory) to create or open.
 
指向一个空结尾字符串。该参数指定了用于创建或打开句柄的对象。

 if *lpFileName is a path, there is a default string size limit of MAX_PATH characters, This limit is related to how the CreateFile function parses paths.
 
如果 lpFileName 的对象是一个路径,则有一个最大字符数的限制。不能超过常量 (MAX_PATH). 这个限制指示了 CreateFile 函数如何解析路径 .

dwDesiredAccess
 Specifies the type of access to the object. An application can obtain read access, write access, read-write access, or device query access, This parameter can be any combination of the following values
 
指定对象的访问方式 , 程序可以获得读访问权 , 写访问权 , 读写访问权或者是询问设备 ("device query") 访问权 .这个参数可以是下列值的任意组合  
含义
 0    Specifies device query access to the object. An application can query device
       attributes without accessing the device.
    
  指定询问访问权 . 程序可以在不直接访问设备的情况下查询设备的属性 .

GENERIC_READ  Specifies read access to the object, Data can be read from the file and the file pointer can be moved. Combine with ENERIC_WRITE for read-write access.
 
指定读访问权.可以从文件中读取数据,并且移动文件指针.可以和 GENERIC_WRITE 组合成为" 读写访问权 ".

GENERIC_WRITE   specifies write access to the object. Data can be written to the file and the file pointer can be moved. Combine with GENERIC_READ fro read-write access
 
指定写访问权.可以从文件中写入数据,并且移动文件指针.可以和GENERIC_READ 组合成为" 读写访问权 ".

dwShareMode
       Set of bit flags that specifies how the object can be shared, If dwShareMode is 0, the object cannot be shared. Subsequent open operations on the object will fail, until the handle is closed.
设置位标志指明对象如休共享.如果参数是0, 对象不能够共享. 后续的打开对象的操作将会失败, 直到该对象的句柄关闭 .

 To share the object, use a combination of one or more of the following values:
 
使用一个或多个下列值的组合来共享一个对象 .
 Meaning
FILE_SHARE_DELETE    WindowsNT: Subsequent open operations on the object           will succeed only if delete access is requested.
后续的仅仅请求删除访问权的打开操作将会成功 .

FILE_SHARE_READ    Subsequent open operations on the object will successd only if read access is requested. 后续的仅仅请求读访问权的打开操作将会成功 .

FILE_SHARE_WRITE   Subsequent open operations on the object will succeed only if write access is requested. 后续的仅仅请求写访问权的打开操作将会成功 .

lpSecurityAttributes
pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes, if lpSecurityAttributes is NULL, the handle cannot be inherited.
指向一个 SECURITY_ATTRIBUTES 结构的指针用于确定如何在子进程中继承这个句柄 . 如果这个参数是 NULL, 则该句柄不可继承.

dwCreationDisposition
      Specifies which action to take on files that exist, and which action to take        when files do not exist. For more information about this parameter, see the remarks section. This parameter must be one of the following values
指定当文件存在或者不存在时如何动作。关于这个参数更多的信息,参考批注部分。这个参数必须是一个或多个下列值。

    Neaning
CREATE_NEW        Creates a new file. The function fails if the specified file already     exists
创建一个新文件 . 如果该文件已经存在函数则会失败 .
CREATE_ALWAYS    Creates a new file. If the file exsts, the function overwrites the       file and clears the existing attributes. 
创建一个新文件. 如果该文件已经存在, 函数将覆盖已存在的文件并清除已存在的文件属性

OPEN_EXISTING    Opens the file. The function fails if the file does not exist.
          See the Remarks section for a discussion of why you should use the      OPEN_EXISTING flag if you are using the CreateFile function for devices,   including the console. 
打开一个文件 , 如果文件不存在函数将会失败 .如查你使用CreateFile 函数为设备装载控制台 . 请查看批注中的 " 为什么使用 OPEN_EXISTING 标志 " 的部分 .
OPEN_ALWAYS     Opens the file, if it exsts. If the file does not exist, the function        creates  the file as if dwCreationDisposition were CREATE_NEW.
如果文件存在 , 打开文件. 如果文件不存在 , 并且参数中有 CREATE_NEW 标志 , 则创建文件 .

TRUNCATE_EXISTING       Opens the file. Once opened, the file is truncated so that its size is zero    bytes The calling process must open the file with at least GENERIC_WRITE access.  The function fails if the file does not exist.
 
打开一个文件 , 每次打开 , 文件将被截至0 字节 . 调用进程必须用 GENERIC_WRITE 访问模式打开文件. 如果文件不存在则函数就会失败 .

dwFlagsAndatributes    Specifies the file attributes and flags for the file.
 
                      为文件指定属性和标志位

               Any combination of the following attributes is acceptable for the dwFlagsAndAttributes parameter, except all other file attributes override FILE_ATTRIBUTE_NORMAL.
该参数可以接收下列属性的任意组合. 除非其它所有的文件属性忽略

Attribute

Meaning

FILE_ATTRIBUTE_ARCHIVE

32 (0x20)

The file should be archived. Applications use this attribute to mark files for backup or removal. 文件将被存档 , 程序使用此属性来标志文件去备份或移除

FILE_ATTRIBUTE_ENCRYPTED

16384 (0x4000)

The file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories. For more information, see File Encryption.

This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also specified.

FILE_ATTRIBUTE_HIDDEN

2 (0x2)

The file is hidden. Do not include it in an ordinary directory listing. 文件被隐藏 , 它不会在一般文件夹列表中被装载 .

FILE_ATTRIBUTE_NORMAL

128 (0x80)

The file does not have other attributes set. This attribute is valid only if used alone. 文件没有被设置任何属性 .

FILE_ATTRIBUTE_OFFLINE

4096 (0x1000)

The data of a file is not immediately available. This attribute indicates that file data is physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute. 文件的数据没有被立即用到。指出正在脱机使用该文件。

FILE_ATTRIBUTE_READONLY

1 (0x1)

The file is read only. Applications can read the file, but cannot write to or delete it. 这个文件只可读取 . 程序可以读文件 , 但不可以在上面写入内容 , 也不可删除 .

FILE_ATTRIBUTE_SYSTEM

4 (0x4)

The file is part of or used exclusively by an operating system. 文件是系统的一部分 , 或是系统专用的 .

FILE_ATTRIBUTE_TEMPORARY

256 (0x100)

The file is being used for temporary storage.

For more information, see the Caching Behavior section of this topic. 文件被使用后,文件系统将努力为(文件的)所有数据的迅迅访问保持一块内存。临时文件应当在程序不用时及时删除。

Flag

Meaning

FILE_FLAG_BACKUP_SEMANTICS

0x02000000

The file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks when the process has SE_BACKUP_NAME and SE_RESTORE_NAME privileges. For more information, see Changing Privileges in a Token.

You must set this flag to obtain a handle to a directory. A directory handle can be passed to some functions instead of a file handle. For more information, see the Remarks section. WINDOWS NT: 指示系统为文件的打开或创建执行一个备份或恢复操作.系统保证调用进程忽略文件的安全选项, 倘若它必须有一个特权. 则相关的特权则是SE_BACKUP_NAMESE_RESTORE_NAME. 你也可以使用这个标志获得一个文件夹的句柄,一个文件夹句柄能够象一个文件句柄一样传给某些 Win32 函数。

FILE_FLAG_DELETE_ON_CLOSE

0x04000000

The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.

If there are existing open handles to a file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode.

Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified. 指示系统在文件所有打开的句柄关闭后立即删除文件 .

FILE_FLAG_NO_BUFFERING

0x20000000

The file or device is being opened with no system caching for data reads and writes. This flag does not affect hard disk caching or memory mapped files.

There are strict requirements for successfully working with files opened with CreateFile using the FILE_FLAG_NO_BUFFERING flag, for details see File Buffering.  指示系统在读写打开的文件或设备时不使用系统缓冲区或缓存,但这个标志对硬盘缓冲区与内存映射文件没有影响。当和 FILE_FLAG_OVERLAPPED 组合 , 该标志给出最大的异步操作量 , 因为 I/O 不依赖内存管理器的异步操作 . 然而 , 一些 I/O 操作将会运行得长一些 , 因为数据没有控制在缓存中 .   当使用 FILE_FLAG_NO_BUFFERING 打开文件进行工作时 , 程序必须达到下列要求 : 文件的存取开头的字节偏移量必须是扇区尺寸的整倍数 文件存取的字节数必须是扇区尺寸的整倍数 . 例如 , 如果扇区尺寸是 512 字节程序就可以读或者写 512,1024 或者 2048 字节 , 但不能够是 335,981 或者 7171字节 进行读和写操作的地址必须在扇区的对齐位置 , 在内存中对齐的地址是扇区尺寸的整倍数 . 一个将缓冲区与扇区尺寸对齐的途径是使用 VirtualAlloc 函数 . 它分配与操作系统内存页大小的整倍数对齐的内存地址 . 因为内存页尺寸和扇区尺寸 --2 都是它们的幂 这块内存在地址中同样与扇区尺寸大小的整倍数对齐. 程序可以通过调用 GetDiskFreeSpace 来确定扇区的尺寸 .

FILE_FLAG_OPEN_NO_RECALL

0x00100000

The file data is requested, but it should continue to be located in remote storage. It should not be transported back to local storage. This flag is for use by remote storage systems. 指明需要文件数据, 但是将继续从远程存储器中接收. 它不会将数据存放在本地存储器中这个标志由远程存储系统或等级存储管理器系统使用 .

FILE_FLAG_OPEN_REPARSE_POINT

0x00200000

Normal reparse point processing will not occur; CreateFile will attempt to open the reparse point. When a file is opened, a file handle is returned, whether or not the filter that controls the reparse point is operational.

This flag cannot be used with the CREATE_ALWAYS flag.

If the file is not a reparse point, then this flag is ignored.

For more information, see the Remarks section.

FILE_FLAG_OVERLAPPED

0x40000000

The file or device is being opened or created for asynchronous I/O. 文件或设备以异步I/O的方式打开或创建

When subsequent I/O operations are completed on this handle, the event specified in the OVERLAPPED structure will be set to the signaled state.

If this flag is specified, the file can be used for simultaneous read and write operations.

If this flag is not specified, then I/O operations are serialized, even if the calls to the read and write functions specify an OVERLAPPED structure.

For information about considerations when using a file handle created with this flag, see the Synchronous and Asynchronous I/O Handles section of this topic.

FILE_FLAG_POSIX_SEMANTICS

0x0100000

Access will occur according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support that naming. Use care when using this option, because files created with this flag may not be accessible by applications that are written for MS-DOS or 16-bit Windows.

FILE_FLAG_RANDOM_ACCESS

0x10000000

Access is intended to be random. The system can use this as a hint to optimize file caching.

This flag has no effect if the file system does not support cached I/O and FILE_FLAG_NO_BUFFERING.

For more information, see the Caching Behavior section of this topic. 指定文件是随机访问 , 这个标志可以使系统优化文件的缓冲 .

FILE_FLAG_SEQUENTIAL_SCAN

0x08000000

Access is intended to be sequential from beginning to end. The system can use this as a hint to optimize file caching.

This flag should not be used if read-behind (that is, backwards scans) will be used.

This flag has no effect if the file system does not support cached I/O and FILE_FLAG_NO_BUFFERING.

For more information, see the Caching Behavior section of this topic. 指定文件将从头到尾连续地访问 . 这个标志可以提示系统优化文件缓冲 . 如果程序在 随机访问文件中移动文件指针 , 优化可能不会发生 ; 然而 , 正确的操作仍然可以得到保证指定这个标志可以提高程序以顺序访问模式读取大文件的性能 , 性能的提高在许多。 程序读取一些大的顺序文件时是异常明显的. 但是可能会有小范围的字节遗漏 .

FILE_FLAG_WRITE_THROUGH

0x80000000

Write operations will not go through any intermediate cache, they will go directly to disk.

For additional information, see the Caching Behavior section of this topic. 指示系统通过快速缓存直接写入磁盘,

HTemplateFile
     
Specifies a handle with GENERIC_READ access to a template file. The template file supplies file attributes and extended attributes for the file being created.
 
GENERIC_READ 访问的模式指定一个句柄到模板文件 . 模板文件在文件开始创建后提供文件属性和扩展属性 .

Return Values返回值

If the function succeeds, the return value is an open handle to the specified file. If the specified file exists before the function call and dwCreation is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.
如果函数成功 , 返回一个打开的指定文件的句柄 . 如果指定文件在函数调用前已经存在并且 dwCreation 参数是 CREATE_ALWAYS 或者 OPEN_ALWAYS, 调用 GetLastError 就会返回 ERROR_ALREADY_EXISTS( 表示函数成功 ). 如果函数文件在调用前不存在则会返回 0.

If the function fails, the return value is INVALID_HANDLE_VALUE.To get extended error information, call GetLastError.
如果函数失败 , 返会值会是 INVALID_HANDLE_VALUE. 更多的错误信息可以调用 GetLastError 来获得 .

原创粉丝点击