现在的位置: 首页 > 综合 > 正文

CreateFile 学习记录

2017年10月13日 ⁄ 综合 ⁄ 共 14008字 ⁄ 字号 评论关闭

The CreateFile function creates or opens a file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, or named pipe. The function returns a handle that
can be used to access an object.

这个函数用于创建或打开:文件流,目录,物理磁盘,卷,控制台缓冲区,磁盘驱动,通信资源,邮槽,管道。(手动翻译,请自己斟酌是否可用)

这个函数返回一个句柄,可用通过句柄访问对应的对象。

Windows Me/98/95: The file system restrictsCreateFile to creating or opening files, and opening COM ports. You cannot create or open the objects that are identified in the first paragraph
of this topic.

HANDLE CreateFile(
  LPCTSTR lpFileName,
  DWORD dwDesiredAccess,
  DWORD dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD dwCreationDisposition,
  DWORD dwFlagsAndAttributes,
  HANDLE hTemplateFile
);

这是来自MSDN library的记录。

这个API来自kernel32.dll,存在两个版本,一个是CreateFileA一个是CreateFileW。


由于这个API的参数比较多,所以做一个记录,方便以后写程序时查询。

①参数一:lpFileName,具体来理解就是文件路径(这里以文件为例)。

lpFileName --->指向文件名的长指针。
[in] A pointer to a null-terminated string(即为在字符串结尾加上'\0'的字符串。) that specifies the name of an object to create or open.

In the ANSI version of this function, the name is limited to MAX_PATH(在我的某个程序中,被定义为#define PATH_MAX 512) characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\"
to the path. For more information, see Naming a File. For information on special device names, seeDefining an MS-DOS Device Name.

To specify a COM port number greater than 9, use the following syntax: "\\\\.\\COM10". This syntax works for all port numbers and hardware that allows COM port numbers to be specified.

To create a file stream, specify the name of the file, a colon, and then the name of the stream. For more information, see File Streams.

Windows Me/98/95: This string must not exceed MAX_PATH characters.

②参数二:dwDesiredAccess---->对象的读权限、写权限、读写权限。即返回句柄后,句柄拥有的权限。

[in] The access to the object, which can be read, write, or both.

For more information, see File Security and Access Rights. You cannot request an access mode that conflicts with the sharing mode that is specified in an open request that has an open handle.

If this parameter is 0 (zero), the application can query file and device attributes without accessing a device. This is useful for an application to determine the size of a floppy disk drive and the formats it supports without
requiring a floppy in a drive. It can also be used to test for the existence of a file or directory without opening them for read or write access.

Access right Description
GENERIC_EXECUTE

FILE_READ_ATTRIBUTES
STANDARD_RIGHTS_EXECUTE
SYNCHRONIZE

GENERIC_READ

FILE_READ_ATTRIBUTES
FILE_READ_DATA
FILE_READ_EA
STANDARD_RIGHTS_READ
SYNCHRONIZE

GENERIC_WRITE

FILE_APPEND_DATA
FILE_WRITE_ATTRIBUTES
FILE_WRITE_DATA
FILE_WRITE_EA
STANDARD_RIGHTS_WRITE
SYNCHRONIZE

如果参数为0,则表示只获取与设备有关 的信息。可用于测试一个文件或目录是否存在,而不使用read和write权限。

③参数三:dwShareMode---->文件共享模式,简单来说,就是其他程序可以使用这个文件的权限,也就是说,在我们使用这个文件时,是否允许别人(别的程序)也对这个文件进行使用。

Value Meaning
FILE_SHARE_DELETE Enables subsequent open operations on an object to request delete access.

Otherwise, other processes cannot open the object if they request delete access.

If this flag is not specified, but the object has been opened for delete access, the function fails.

Windows Me/98/95: This flag is not supported.

FILE_SHARE_READ Enables subsequent open operations on an object to request read access.

Otherwise, other processes cannot open the object if they request read access.

If this flag is not specified, but the object has been opened for read access, the function fails.

FILE_SHARE_WRITE Enables subsequent open operations on an object to request write access.

Otherwise, other processes cannot open the object if they request write access.

If this flag is not specified, but the object has been opened for write access, the function fails.

④参数四:lpSecurityAttributes --->安全属性。指向SECURITY_ATTRIBUTES结构体的指针。

typedef struct _SECURITY_ATTRIBUTES 
{
    DWORD      nLength;
    LPVOID     lpSecurityDescriptor;
    BOOL       bInheritHandle;
} SECURITY_ATTRIBUTES,*PSECURITY_ATTRIBUTES,*LPSECURITY_ATTRIBUTES;

[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not the returned handle can be inherited by child processes.(是否允许被子进程继承。)

If lpSecurityAttributes is NULL, the handle cannot be inherited.(如果为NULL,则表示不能被继承)

The lpSecurityDescriptor member of the structure specifies a security descriptor for an object. IflpSecurityAttributes is NULL, the object gets a default security descriptor. The access control lists
(ACL) in the default security descriptor for a file or directory are inherited from its parent directory.

The target file system must support security on files and directories for this parameter to have an effect on them, which is indicated whenGetVolumeInformation returns FS_PERSISTENT_ACLS.

CreateFile ignores lpSecurityDescriptor when opening an existing file, but continues to use the other structure members.

⑤参数五:dwCreationDisposition -->文件存在或不存在时的操作。

[in] An action to take on files that exist and do not exist.

For more information, see the Remarks section of this topic.

This parameter must be one of the following values.

Value Meaning
CREATE_ALWAYS Creates a new file, always.总是创建一个新文件

If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes, and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that theSECURITY_ATTRIBUTES structure
specifies.

如果文件已经存在,则改写这个文件,清除存在的属性。

CREATE_NEW Creates a new file.创建新文件,如果文件存在,则返回失败。

The function fails if a specified file exists.

OPEN_ALWAYS Opens a file, always.总是打开文件,如果不存在则创建。

If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.

OPEN_EXISTING Opens a file.打开一个文件。

The function fails if the file does not exist.如果文件不存在,则返回失败。

For more information, see the Remarks section of this topic.

TRUNCATE_EXISTING

Opens a file and truncates it so that its size is 0 (zero) bytes.

将现有文件的长度变成0,如果文件不存在,则返回失败。在CreateFile的第二个参数中必须为GENERIC_WRITE。

The function fails if the file does not exist.

The calling process must open the file with the GENERIC_WRITE access right.

⑥参数六:dwFlagsAndAttbutes --->文件标识和属性。比如隐藏、只读等。

[in] The file attributes and flags.

This parameter can include any combination of the file attributes. All other file attributes override FILE_ATTRIBUTE_NORMAL.

When CreateFile opens a file, it combines the file flags with existing file attributes, and ignores any supplied file attributes.

The following file attributes and flags are used only for file objects, not other types of objects thatCreateFile creates.

Attribute Meaning
FILE_ATTRIBUTE_ARCHIVE A file should be archived. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_ENCRYPTED A 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 A file is hidden. Do not include it in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL A file does not have other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_OFFLINE 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 A file is read only. Applications can read the file, but cannot write to or delete it.
FILE_ATTRIBUTE_SYSTEM A file is part of or used exclusively by an operating system.
FILE_ATTRIBUTE_TEMPORARY A file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed.
In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.
FILE_ATTRIBUTE_VIRTUAL A file is a virtual file.

This parameter can also include any combination of the following flags.

Flag Meaning
FILE_FLAG_BACKUP_SEMANTICS A 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 can 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 Obtaining A Handle to a Directory.

Windows Me/98/95: This flag is not supported.

FILE_FLAG_DELETE_ON_CLOSE The system deletes a file 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 The system opens a file with no system caching. This flag does not affect hard disk caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations
of the memory manager. However, some I/O operations take more time, because data is not being held in the cache. Also, the file metadata may still be cached. To flush the metadata to disk, use theFlushFileBuffers function.

An application must meet certain requirements when working with files that are opened with FILE_FLAG_NO_BUFFERING:

  • File access must begin at byte offsets within a file that are integer multiples of the volume sector size.
  • File access must be for numbers of bytes that are integer multiples of the volume sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, 1536, or 2048 bytes, but not of 335, 981, or 7171 bytes.
  • Buffer addresses for read and write operations should be sector aligned, which means aligned on addresses in memory that are integer multiples of the volume sector size. Depending on the disk, this requirement may not be enforced.

One way to align buffers on integer multiples of the volume sector size is to useVirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size.
Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume sector size. Memory pages are 4-8 KB in size; sectors are 512 bytes (hard disks) or 2048 bytes (CD), and therefore,
volume sectors can never be larger than memory pages.

An application can determine a volume sector size by calling the GetDiskFreeSpace function.

FILE_FLAG_OPEN_NO_RECALL 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 The system inhibits the reparse behavior of NTFS file system reparse points. 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.
FILE_FLAG_OVERLAPPED The file is being opened or created for asynchronous I/O. When the operation is complete, the event specified in theOVERLAPPED structure is set to the signaled state. Operations that take a significant amount of time to process
return ERROR_IO_PENDING.

If this flag is specified, the file can be used for simultaneous read and write operations. The system does not maintain the file pointer, therefore you must pass the file position to the read and write functions in theOVERLAPPED structure
or update the file pointer.

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

FILE_FLAG_POSIX_SEMANTICS A file is accessed 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 A file is accessed randomly. The system can use this as a hint to optimize file caching.
FILE_FLAG_SEQUENTIAL_SCAN A file is accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur. However, correct operation is still
guaranteed.

Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges
of bytes.

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

FILE_FLAG_WRITE_THROUGH The system writes through any intermediate cache and goes directly to disk.

If FILE_FLAG_NO_BUFFERING is not also specified, so that system caching is in effect, then the data is written to the system cache, but is flushed to disk without delay.

If FILE_FLAG_NO_BUFFERING is also specified, so that system caching is not in effect, then the data is immediately flushed to disk without going through the system cache. The operating system also requests a write-through the hard disk cache to persistent
media. However, not all hardware supports this write-through capability.

           The dwFlagsAndAttributes parameter can also contain Security Quality of Service information. For more information, see      Impersonation Levels. When the calling application specifies the SECURITY_SQOS_PRESENT
flag, the dwFlagsAndAttributes parameter can contain one or more of the following values.

Value Meaning
SECURITY_ANONYMOUS Impersonates a client at the Anonymous impersonation level.
SECURITY_CONTEXT_TRACKING The security tracking mode is dynamic. If this flag is not specified, the security tracking mode is static.
SECURITY_DELEGATION Impersonates a client at the Delegation impersonation level.
SECURITY_EFFECTIVE_ONLY Only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available.

This allows the client to limit the groups and privileges that a server can use while impersonating the client.

SECURITY_IDENTIFICATION Impersonates a client at the Identification impersonation level.
SECURITY_IMPERSONATION Impersonate a client at the impersonation level.

               一般使用FILE_ATTRIBUTE_NORMAL即可,所有的属性都可以结合使用,使用异或的方式。

⑦参数七:hTemplateFile  --->这个参数没弄明白。我一般写为NULL

[in] A handle to a template file with the GENERIC_READ access right. The template file supplies file attributes and extended attributes for the file that is being created. This parameter can be NULL.

When opening an existing file, CreateFile ignores the template file.

When opening a new EFS-encrypted file, the file inherits the DACL from its parent directory.

Windows Me/98/95: The
hTemplateFile
parameter must be NULL. If you supply a handle, the call fails andGetLastError returns ERROR_NOT_SUPPORTED.

大致的参数就是这样,具体的我们来看一个实例。这样方便具体的理解。

HANDLE hFile = CreateFile(szFilePath,GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
                          NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if (hFile == INVALID_HANDLE_VALUE)
	{
		MessageBox("打开文件失败");
		return;
	}

Return Value

If the function succeeds, the return value is an open handle to a specified file. If a specified file exists before the function call anddwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to
GetLastError returns ERROR_ALREADY_EXISTS, even when the function succeeds. If a file does not exist before the call,GetLastError returns 0 (zero).

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, callGetLastError.

抱歉!评论已关闭.