网站首页  词典首页

请输入您要查询的函数:

 

术语 createfile
释义 CreateFile
语法:
C++
HANDLE WINAPI CreateFile(
__in LPCTSTR lpFileName,
__in DWORD dwDesiredAccess,
__in DWORD dwShareMode,
__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
__in DWORD dwCreationDisposition,
__in DWORD dwFlagsAndAttributes,
__in_opt HANDLE hTemplateFile
);
CreateFile Function
创建或打开一个文件或I / O设备。最常用的I / O设备如下:文件,文件流,目录,物理磁盘,卷,控制台缓冲区,磁带驱动器,通信资源,邮筒和管道。该函数返回一个句柄,可用于访问文件或为我各类设备/ O的文件或设备,并根据旗帜和属性指定。
要执行一个交易操作,在一个句柄,可用于这一行动的结果进行交易的I / O,使用CreateFileTransacted功能。
参数
lpFileName [in]
该文件或设备的名称创建或打开。
在此函数的ANSI版本,名称被限制为MAX_PATH字符。为了延长此限制,以32,767宽字符,调用的功能和前面加上“\\ Unicode版本\\?\\”的路径。有关更多信息,请参见命名一个文件。
有关特殊设备名称的详细信息,请参阅定义一个MS - DOS设备名。
要创建一个文件流,指定文件,冒号名称,然后流的名称。有关更多信息,请参阅文件流。
dwDesiredAccess [in]
所要求的访问文件或设备,它可以概括为:读,写,都还是没有(零)。
最常用的值是GENERIC_READ,GENERIC_WRITE,或两者(GENERIC_READ | GENERIC_WRITE)。有关更多信息,请参阅通用访问权限和文件安全性和访问权限。
如果此参数为0,应用程序可以查询,例如文件,目录,或没有上网设备的某些元数据属性的文件或设备,即使GENERIC_READ访问将被拒绝。
您不能要求一个访问模式相冲突的共享模式,是由在一个开放的要求,已经有一个打开句柄dwShareMode参数指定。
有关更多信息,请参阅本主题的创建和打开文件备注部分。
dwShareMode [in]
该文件或设备,它可以读,写,两个,删除,所有这些,都要求或共享模式(参考下表)。访问请求属性或扩展属性不受此标志。
如果这个参数是零和CreateFile成功,文件或设备不能共享,不能打开,直至处理的文件或设备再次关闭。有关详细信息,请参见备注部分。
您不能要求共享模式相冲突的访问模式是在现有的请求时,指定的打开句柄。CreateFile将失败,并且GetLastError函数将返回ERROR_SHARING_VIOLATION。
为了使一个进程共享一个文件或设备,而另一进程有打开文件或设备,使用一个或多个下列值兼容的组合。如需有关此dwDesiredAccess参数与参数的有效组合信息,请参阅创建和打开文件。
注意:为每个打开的句柄继续有效,直至该关闭的处理共享选项,不管过程中。
ValueMeaning
0
打开文件或设备,如果他们的要求删除,读,写访问0x00000000Prevents其他进程。
FILE_SHARE_DELETE
0x00000004Enables在一个文件或设备随后打开操作要求删除访问。
否则,其他进程无法打开文件或设备,如果他们的要求删除访问。
如果此标志没有被指定,但该文件或设备已打开删除访问,函数失败。
注意:删除访问允许都删除和重命名操作。
FILE_SHARE_READ
0x00000001Enables在一个文件或设备随后打开操作要求读取访问。
否则,其他进程无法打开文件或设备,如果他们的要求读访问。
如果此标志没有被指定,但该文件或设备已读访问打开,该功能失败。
FILE_SHARE_WRITE
0x00000002Enables在一个文件或设备随后打开操作要求写访问。
否则,其他进程无法打开文件或设备,如果他们的要求写访问。
如果此标志没有被指定,但该文件或设备已开放了写入访问或与写访问文件映射,函数失败。
lpSecurityAttributes [中,可选]
一个SECURITY_ATTRIBUTES结构,它包含两个独立但相关的数据成员:一个可选的安全描述符,和一个布尔值,决定是否返回的句柄可以被继承的子进程的指针。
此参数可以为NULL。
如果该参数为NULL,CreateFile返回处理不能由任何子继承过程的应用程序可能创建的文件或与返回句柄得到默认的安全描述相关设备。
结构的lpSecurityDescriptor成员指定了一个文件或设备SECURITY_DESCRIPTOR。如果这个成员是NULL,则文件或返回的句柄分配默认的安全描述相关设备。
CreateFile忽略lpSecurityDescriptor成员在打开一个现有的文件或设备,但仍继续使用bInheritHandle成员。
结构的bInheritHandle成员指定是否返回的句柄可以继承。
有关详细信息,请参见备注部分。
dwCreationDisposition [in]
一个采取行动的文件或设备存在或不存在。
对于设备比其他的文件,这个参数通常设置为OPEN_EXISTING。
有关详细信息,请参见备注部分。
此参数必须是下列值,不能结合起来:
ValueMeaning
CREATE_ALWAYS
2Creates一个新的文件,总是如此。
如果指定的文件存在并且是可写的,功能覆盖该文件,函数执行成功,最后,错误代码设置为ERROR_ALREADY_EXISTS(183)。
如果指定的文件不存在,是一个有效的路径,一个新的文件被创建,函数成功,最后,错误代码设置为零。
有关更多信息,请参阅本主题的备注部分。
CREATE_NEW
1Creates一个新的文件,只有当它不存在。
如果指定的文件存在,函数失败并在最后一错误代码设置为ERROR_FILE_EXISTS(80)。
如果指定的文件不存在,是一个有效的路径写的地理位置,创建新文件。
OPEN_ALWAYS
4Opens一个文件,总是如此。
如果指定的文件存在,函数成功,最后,错误代码设置为ERROR_ALREADY_EXISTS(183)。
如果指定的文件不存在,是一个有效的路径写的位置,函数创建一个文件和最后的错误代码设置为零。
OPEN_EXISTING
3Opens文件或设备,只有当它存在。
如果指定的文件或设备不存在,函数失败并在最后一错误代码设置为ERROR_FILE_NOT_FOUND(2)。
欲了解更多有关设备的信息,请参见备注部分。
TRUNCATE_EXISTING
5Opens一个文件,截断它,以便它的大小为0字节,只有当它存在。
如果指定的文件不存在,函数失败并在最后一错误代码设置为ERROR_FILE_NOT_FOUND(2)。
调用过程必须公开,作为部分dwDesiredAccess参数与GENERIC_WRITE设置位文件。
将dwFlagsAndAttributes [in]
该文件或设备属性和标志,FILE_ATTRIBUTE_NORMAL是最常见的文件的默认值。
此参数可包括任何可用文件属性组合(FILE_ATTRIBUTE_ *)。所有其他文件属性覆盖FILE_ATTRIBUTE_NORMAL。
此参数也可以包含标志的组合(FILE_FLAG_ *的文件或设备控制)的缓存行为,接入方式,和其他特殊用途的标志。这些结合起来,任何FILE_ATTRIBUTE_ *值。
此参数也可以包含通过指定SECURITY_SQOS_PRESENT旗信息安全服务质量。附加SQOS有关的标志信息显示在以下表中的属性和标志表。
注意当CreateFile打开一个现有的文件,它通常结合了文件的文件属性标志现有的文件,并忽略任何文件属性,作为将dwFlagsAndAttributes的一部分提供。有特殊情况的详细的创建和打开文件。
以下文件的属性和标志有些人可能只适用于文件,不一定是所有的设备CreateFile可以打开其他类型。有关其他信息,请参阅本主题的创建和打开文件备注部分。
对于更高级的访问文件的属性,见SetFileAttributes。有关的所有文件的完整列表属性与他们的价值观和说明,请参阅文件属性。
AttributeMeaning
FILE_ATTRIBUTE_ARCHIVE
32(0x20)的文件应存档。应用程序使用此属性来庆祝备份或删除的文件。
FILE_ATTRIBUTE_ENCRYPTED
16384(0x4000)的文件或目录进行加密。一个文件,这意味着,在文件中的所有数据进行加密。对于目录,这意味着加密是新创建的文件和子目录的默认。有关更多信息,请参阅文件加密。
此标志,如果FILE_ATTRIBUTE_SYSTEM也指定的效果。
FILE_ATTRIBUTE_HIDDEN
2(0x2),该文件是隐藏的。不包括一般的目录清单它。
FILE_ATTRIBUTE_NORMAL
128(0x80),该文件没有其他属性。此属性是有效的,只有单独使用。
FILE_ATTRIBUTE_OFFLINE
4096(0x1000)一个文件数据还不清楚。此属性文件中的数据表明,在身体移动到脱机存储。该属性是使用远程存储,层次化存储管理软件。应用程序不应随意更改此属性。
FILE_ATTRIBUTE_READONLY
1(0x1),该文件是只读的。应用程序可以读取该文件,但不能写入或删除。
FILE_ATTRIBUTE_SYSTEM
4(0x4)文件的一部分或使用的操作系统为主。
FILE_ATTRIBUTE_TEMPORARY
256(0x100),该文件被用于临时存储。
有关更多信息,请参阅本主题的缓存行为部分。
FlagMeaning
FILE_FLAG_BACKUP_SEMANTICS
0x02000000The文件被打开或备份或还原操作创建。该系统保证了调用进程覆盖文件时的安全检查过程SE_BACKUP_NAME和SE_RESTORE_NAME特权。有关更多信息,请参阅更改权限的令牌。
您必须设置此标志以获取句柄到一个目录。一个目录句柄可以被传递到某些职能而不是一个文件句柄。有关详细信息,请参见备注部分。
FILE_FLAG_DELETE_ON_CLOSE
0x04000000The文件被删除后,它的句柄关闭,其中包括指定的处理和其他所有打开或复制立即处理所有。
如果有现有的打开的句柄到一个文件,调用失败,除非他们都与FILE_SHARE_DELETE共享模式打开。
随后打开该文件的请求失败,除非FILE_SHARE_DELETE分享模式是指定的。
FILE_FLAG_NO_BUFFERING
0x20000000The文件或设备正在打开,没有进行数据缓存系统读取和写入。这个标志不影响硬盘缓存或内存映射文件。
有成功CreateFile打开与使用FILE_FLAG_NO_BUFFERING标志档案工作严格要求,详情见文件缓冲。
FILE_FLAG_OPEN_NO_RECALL
0x00100000The文件数据请求,但应继续在远程存储位置。它不应该运回本地存储。这个标志由远程存储系统的使用。
FILE_FLAG_OPEN_REPARSE_POINT
0x00200000Normal分析点处理将不会发生;CreateFile将尝试打开重分析点。当一个文件被打开,文件句柄返回,是否过滤器,控制分析点已开始运作。
这个标志不能用于与CREATE_ALWAYS标志。
如果该文件不是一个分析点,那么这个标志被忽略。
有关详细信息,请参见备注部分。
FILE_FLAG_OVERLAPPED
0x40000000The文件或设备正在打开或创建的异步I / O的
当随后的I / O操作在此处理,在OVERLAPPED结构指定的事件将被设置为有信号状态完成。
如果这个标志被指定,该文件可用于同步读取和写入操作。
这标志,如果没有指定,则I / O操作被序列化,即使调用读写功能指定一个OVERLAPPED结构。
有关注意事项的信息时,使用文件处理这个标志创建的,请同步和异步I / O负责处理这个问题一节。
FILE_FLAG_POSIX_SEMANTICS
0x0100000Access将出现按照POSIX的规则。这包括允许多个文件的名称,只在不同的情况下,对文件系统,支持这一命名。时请务必小心使用此选项,因为文件与此标志创建的可能无法访问的应用程序的编写的MS - DOS或16位Windows。
FILE_FLAG_RANDOM_ACCESS
0x10000000Access的目的是随机的。该系统可以使用提示此文件缓存优化。
此标志如果文件系统不支持缓存的I / O和FILE_FLAG_NO_BUFFERING效果。
有关更多信息,请参阅本主题的缓存行为部分。
FILE_FLAG_SEQUENTIAL_SCAN
0x08000000Access拟从开始到结束顺序。该系统可以使用提示此文件缓存优化。
这个标志应该不应该使用的只读后面(即,向后扫描)将被使用。
此标志如果文件系统不支持缓存的I / O和FILE_FLAG_NO_BUFFERING效果。
有关更多信息,请参阅本主题的缓存行为部分。
FILE_FLAG_WRITE_THROUGH全方位
0x80000000Write行动将不会通过任何中间缓存,他们会直接到磁盘。
有关其他信息,请参阅本主题的缓存行为部分。
在将dwFlagsAndAttributes参数还可以指定信息安全服务质量。有关更多信息,请参阅模拟Level。当调用应用程序指定为将dwFlagsAndAttributes一部分SECURITY_SQOS_PRESENT标志,它也可以包含一个或多个下列值。
安全flagMeaning
SECURITY_ANONYMOUSImpersonates客户在匿名模拟级别。
SECURITY_CONTEXT_TRACKINGThe安全跟踪方式是动态的。如果此标志没有被指定,安全跟踪方式是静态的。
SECURITY_DELEGATIONImpersonates客户在模拟级别代表团。
SECURITY_EFFECTIVE_ONLYOnly启用的客户端的安全方面问题的可用服务器。如果您不指定此标志,客户端的安全上下文中可用的所有方面。
这允许客户端限制和特权的群体,一个服务器可以同时使用模拟客户端。
SECURITY_IDENTIFICATIONImpersonates客户身份查验模拟级别。
SECURITY_IMPERSONATIONImpersonate客户在模拟级别。这是默认的行为如果没有其他指定标志旗与SECURITY_SQOS_PRESENT沿。
hTemplateFile [中,可选]
有效的句柄到模板文件与GENERIC_READ访问的权利。提供的模板文件的文件属性和正在创建的文件的扩展属性。
此参数可以为NULL。
当打开一个现有的文件,忽略这个参数CreateFile。
在开启了一个新的加密文件,该文件从它继承父目录的自由访问控制列表。有关其他信息,请参阅文件加密
返回值
如果函数成功,返回值是一个开放的句柄指定的文件,设备,命名管道或邮件插槽。
如果函数失败,返回值是INVALID_HANDLE_VALUE。为了获得更多错误信息,调用GetLastError。
备注
最初CreateFile专门为文件的交互,但已经扩展和增强,包括大多数其他类型的I / O设备和机制,提供给Windows开发。本节试图涵盖不同的开发时可能遇到的问题在不同情况下使用CreateFile和不同的I / O类型。该文尝试使用Word文件只有在特别是指在一个文件系统上的实际文件存储的数据。然而,文件的某些用途可能是指一个更广泛的I / O对象,支持文件等机制。这一文件的自由一词的使用是特别普遍的常量名和由于历史的原因,前面提到的参数名。
当一个应用程序在使用完对象CreateFile返回处理,使用CloseHandle函数关闭处理。这不仅可以节省系统资源,但可以有更多的像共享文件或设备,并承诺数据到磁盘东西的影响。具体是说在本专题内适当。
Windows Server 2003和Windows XP/2000操作系统:发生共享冲突如果试图打开远程计算机上的文件或目录时,删除了dwDesiredAccess参数值是删除访问国旗与其他旗帜或运算访问,远程文件或目录未开立FILE_SHARE_DELETE。为了避免在这种情况下共享冲突,开放与远程删除访问文件或目录的权利只,或调用没有首先打开的DeleteFile文件或目录的删除。
某些文件系统,如NTFS文件系统,支持压缩或个别文件和目录加密。卷上有一个与此支持下,一个新的文件挂载的文件系统继承了压缩和加密的目录的属性。
您不能使用CreateFile来控制文件或目录压缩,解压缩,或解密。有关更多信息,请参阅创建和打开文件,文件压缩和解压,和文件加密。
Windows Server 2003和Windows XP/2000操作系统:为了向后兼容的目的,不适用CreateFile继承规则,当您指定一个lpSecurityAttributes安全描述符。为了支持继承,后来查询功能,在此文件的安全描述符可能启发式确定和报告的继承生效。有关更多信息,请参阅可继承ACE的自动繁殖。
如前所述,如果lpSecurityAttributes参数为NULL,CreateFile返回处理不能由任何子继承处理您的应用程序可能创建的。以下有关此参数也适用于:
如果bInheritHandle成员变量是不是虚假的,这是任何非零值,然后把手可以继承。因此,这种结构是至关重要的成员是正确初始化为FALSE,如果您不打算要句柄可继承。
访问控制列表(ACL)中的默认安全描述符文件或目录都继承自它的父目录。
目标文件系统必须支持lpSecurityDescriptor成员的安全有一个对他们的影响,这可以通过使用GetVolumeInformation确定的文件和目录。
符号链接行为
如果调用此函数创建一个文件,没有任何行为的改变。此外,考虑下列资料FILE_FLAG_OPEN_REPARSE_POINT:
如果FILE_FLAG_OPEN_REPARSE_POINT指定:
如果现有的文件被打开,这是一个符号链接,返回句柄是一个句柄符号链接。
如果TRUNCATE_EXISTING或FILE_FLAG_DELETE_ON_CLOSE指定,受影响的文件是一个符号链接。
如果未指定FILE_FLAG_OPEN_REPARSE_POINT:
如果现有的文件被打开,这是一个符号链接,返回句柄是一个句柄到目标。
如果CREATE_ALWAYS,TRUNCATE_EXISTING,或FILE_FLAG_DELETE_ON_CLOSE指定,受影响的文件是目标。
缓存行为
为将dwFlagsAndAttributes参数的可能值中有几个使用CreateFile来控制或影响如何与句柄是由系统缓存相关的数据。它们是:
FILE_FLAG_NO_BUFFERING
FILE_FLAG_RANDOM_ACCESS
FILE_FLAG_SEQUENTIAL_SCAN
FILE_FLAG_WRITE_THROUGH全方位
FILE_ATTRIBUTE_TEMPORARY
如果这些标志没有指定,系统将使用默认的通用缓存方案。否则,系统缓存行为指明每个标志。
这些标志有些不应该合并。例如,与FILE_FLAG_SEQUENTIAL_SCAN结合FILE_FLAG_RANDOM_ACCESS是弄巧成拙。
指定FILE_FLAG_SEQUENTIAL_SCAN标志可以提高应用软件的性能阅读使用顺序访问大型文件。性能收益可以更加明显的应用主要是大文件的读取顺序,但偶尔跳过小范围的字节前进。如果应用程序移动的随机存取文件指针,优化缓存性能最有可能不会发生。但是,正确的操作仍然是保障。
FILE_FLAG_WRITE_THROUGH全方位的旗帜和FILE_FLAG_NO_BUFFERING是独立的,可以合并。
如果FILE_FLAG_WRITE_THROUGH全方位的使用,但FILE_FLAG_NO_BUFFERING也没有指定,使系统缓存的效果,然后数据被写入到系统缓存,但立即刷新到磁盘。
如果FILE_FLAG_WRITE_THROUGH全方位和FILE_FLAG_NO_BUFFERING都是指定的,所以系统缓存没有生效,然后数据被立即刷新到磁盘的情况下通过Windows系统缓存此案。该操作系统还要求通过写硬盘的本地硬件缓存持久性媒体。
注意:并非所有硬盘的硬件支持,通过这写能力。
FILE_FLAG_NO_BUFFERING标志的正确使用,需要考虑的特殊应用。有关更多信息,请参阅文件缓冲。
阿写员工透过FILE_FLAG_WRITE_THROUGH全方位的要求,也使NTFS刷新任何元数据的变化,例如一个时间戳更新或重命名操作,从处理请求的结果。为此,该FILE_FLAG_WRITE_THROUGH标志是经常与作为调用FlushFileBuffers FILE_FLAG_NO_BUFFERING标志更换后,每次写功能,从而导致不必要的性能下降。使用这些标志一起,就可避免这些惩罚。有关的文件和数据高速缓存的一般信息,请参阅文件缓存。
当FILE_FLAG_NO_BUFFERING与FILE_FLAG_OVERLAPPED相结合,最大限度地异步旗帜的表现,因为I / O并不依赖于内存管理器的同步操作。然而,一些I / O操作需要更多的时间,因为数据不被缓存中举行。此外,文件元数据可能仍然被缓存(例如,当创建一个空文件)。为确保数据刷新到磁盘,使用FlushFileBuffers函数。
指定FILE_ATTRIBUTE_TEMPORARY属性导致文件系统,以避免写入数据传回的海量存储如果有足够的缓存内存可用,因为应用程序删除处理后,关闭一个临时文件。在这种情况下,系统可以完全避免写数据。虽然不直接控制数据相同的方式缓存为前面提到的标志,FILE_ATTRIBUTE_TEMPORARY属性并告诉系统拥有多达系统缓存中可能没有文字,因此可能是某些应用的关注。
文件
如果您重命名或删除一个文件,然后还原紧接着,系统搜索的文件信息缓存来恢复。缓存信息包括其短期/长期的名字对,创建时间。
如果您调用一个文件之前,作为先前调用结果的DeleteFile删除CreateFile,功能失败。该操作系统的延迟发布文件删除,直到所有的文件句柄关闭。 GetLastError返回ERROR_ACCESS_DENIED。
在dwDesiredAccess参数可以是零,允许应用程序查询文件,而不访问该文件如果应用程序有足够的安全设置运行属性。这是有用的为一个文件的情况下测试的存在开放阅读和/或写访问,或以获取有关文件或目录的其他统计资料。见获取和设置文件信息和GetFileInformationByHandle
Windows Server 2003和Windows XP/2000操作系统:如果CREATE_ALWAYS和FILE_ATTRIBUTE_NORMAL是指定CreateFile失败并设置最后一个错误的ERROR_ACCESS_DENIED如果该文件存在,并有FILE_ATTRIBUTE_HIDDEN或FILE_ATTRIBUTE_SYSTEM属性。为了避免错误,指定为现有的文件相同的属性。
当一个应用程序创建的文件在网络中,最好是使用GENERIC_READ | GENERIC_WRITE的dwDesiredAccess比单独使用GENERIC_WRITE。由此产生的代码速度更快,因为重定向可以使用缓存管理器和发送更多的数据较少的中小型企业。这种组合也避免了一个问题,即以书面向在网络上文件可以偶尔返回ERROR_ACCESS_DENIED。
有关更多信息,请参阅创建和打开文件。
同步和异步I / O拉手
CreateFile为创建一个文件或设备句柄同步或异步。阿同步处理的行为,这样的I / O函数调用使用该处理被封锁,直至他们完成,而异步文件句柄可以使系统能够从我立刻返回/ O函数调用,他们是否完成了I / O操作或不。如前所述,这种同步与异步行为是在将dwFlagsAndAttributes参数FILE_FLAG_OVERLAPPED指定确定。有一些复杂性和潜在的缺陷时,使用异步I / O有更多信息,请参阅同步和异步I / O。
文件流
在NTFS文件系统,可以使用CreateFile来创建一个文件内单独流。有关更多信息,请参阅文件流。
目录
应用程序不能使用CreateFile创建一个目录,因此只有OPEN_EXISTING值为dwCreationDisposition有效期为这个用例。要创建一个目录,应用程序必须调用CreateDirectory或CreateDirectoryEx。
要打开一个目录使用CreateFile,指定作为将dwFlagsAndAttributes一部分FILE_FLAG_BACKUP_SEMANTICS标志。适当的安全检查时,仍适用这个标志是没有SE_BACKUP_NAME和SE_RESTORE_NAME特权使用。
当使用CreateFile打开一个在FAT或FAT32文件系统卷碎片整理的目录,不指定MAXIMUM_ALLOWED访问权限。访问目录如果被拒绝这样做。指定GENERIC_READ访问权限代替。
有关更多信息,请参阅关于目录管理
物理磁盘和卷
直接访问磁盘或卷的限制。有关更多信息,请参阅“更改文件系统和存储堆栈限制直接磁盘访问和Windows Vista中直接访问量和Windows Server 2008”的帮助和支持http://support.microsoft知识库。 com/kb/942448。
服务器2003和Windows XP/2000:直接进入磁盘或卷没有以这种方式限制的Windows。
您可以使用CreateFile函数打开一个物理磁盘驱动器或卷,它返回一个直接访问存储设备(DASD)句柄,可以与使用DeviceIoControl函数。这使您能够访问磁盘或卷直接,例如因为这些磁盘的分区表数据。然而,这种类型的访问也暴露了磁盘驱动器或卷潜在的数据损失,因为一个不正确的写入到磁盘使用这种机制可以使内容无法进入操作系统。为了保证数据的完整性,一定要熟悉熟悉的DeviceIoControl,以及如何与其它API的行为直接访问不同的处理,而不是文件系统处理。
以下要求必须满足这样的调用成功:
调用者必须具有管理权限。有关更多信息,请运行特权。
该dwCreationDisposition参数必须有OPEN_EXISTING标志。
当打开一个卷或软盘的dwShareMode参数必须有FILE_SHARE_WRITE标志。
注意dwDesiredAccess参数可以是零,使设备应用程序查询无需访问设备的属性。这是非常有用的应用程序,以确定软盘驱动器的大小和格式,它无需在一个软盘驱动器支持,例如。它也可以用于读取,而不需要更高层次的统计数据读/写权限。
当打开一个物理驱动器X的lpFileName字符串应该是以下形式:\\ \\。\\的PhysicalDriveX。硬盘数字从零开始。下表显示的物理驱动器字符串的一些例子。
StringMeaning
\\ \\。\\ PhysicalDrive0Opens第一个物理驱动器。
\\ \\。\\ PhysicalDrive2Opens第三个物理驱动器。
要获得一个卷物理驱动器标识符,打开句柄的数量和调用IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS DeviceIoControl函数。这种控制代码返回的磁盘数目和数量的一个或多个扩展每个抵销;一个卷可以跨多个物理磁盘。
对于打开一个物理驱动器的例子,看到的DeviceIoControl调用。
当打开一个卷或驱动器可移动媒体(例如,软盘驱动器或闪存U盘),在lpFileName字符串应该是以下形式:\\ \\。\\ X:。不要使用一个尾部反斜杠(\\),这表明了一个驱动器的根目录。下表显示的驱动器字符串的一些例子。
StringMeaning
\\ \\。\\答:打开软盘驱动器A
\\ \\。\\荤:打开C:卷。
\\ \\。\\ ?:\\打开的C文件系统:卷。
您还可以提到其卷名称卷。有关更多信息,请参见命名一个卷。
阿卷包含一个或多个安装的文件系统。处理量可开在特定的文件系统决定非缓存,即使在非缓存选项不CreateFile中指定。您应该假设所有文件系统微软开放的空间处理的非缓存。对限制非缓存的I / O文件,也适用于卷。
文件系统可能会或不会要求缓冲区对齐即使数据是非缓存。但是,如果非缓存选项打开时指定卷,缓冲区对齐,无论是执行卷上的文件系统。我们建议所有文件,打开卷处理它们的非缓存系统,并按照非缓存的I / O的限制。
注意:要读取或写入该卷的最后几个部门,则必须调用DeviceIoControl和指定FSCTL_ALLOW_EXTENDED_DASD_IO。这表明该文件系统驱动程序不执行任何分区的I / O边界检查读或写调用。相反,边界检查是由设备驱动程序。
换设备
在IOCTL_CHANGER_ *为的DeviceIoControl接受句柄更换设备控制代码。要打开更换设备,使用以下形式的文件名:\\ \\。\\ Changerx其中x是一个数字,指示哪个设备打开,从零开始。要打开一个是在C或C书面申请,更换设备零+ +,请使用以下文件名:“\\ \\ \\ \\。\\ \\ Changer0”。
磁带机
You can open tape drives by using a file name of the following form: \\\\.\\TAPEx where x is a number that indicates which drive to open, starting with tape drive zero.要打开一个是在C或C书面申请,磁带驱动器零+ +,请使用以下文件名:“\\ \\ \\ \\。\\ \\ TAPE0”。
有关更多信息,请参阅备份。
通信资源
CreateFile函数可以创建一个处理诸如串口COM1到通信资源。通信资源,dwCreationDisposition参数必须OPEN_EXISTING的dwShareMode参数必须是零(独占访问)和hTemplateFile参数必须是NULL。读,写或读/写访问可以指定,把手可以开放给重叠I / O
要指定一个COM端口号大于9,使用下面的语法:“\\ \\。\\ COM10”。这个语法工程所有端口号和硬件,允许COM端口号指定。
欲了解更多有关信息通报信息,请参阅通讯。
控制台
CreateFile函数可以创建一个句柄控制台输入(CONIN $)。如果能公开处理因继承或重复的结果它,它也可以创建一个句柄活动(CONOUT $)屏幕缓冲区。调用进程必须重视继承控制台或AllocConsole函数分配之一。对于控制台处理,设置为如下CreateFile参数。
ParametersValue
lpFileNameUse的CONIN $值,以指定控制台输入。
使用CONOUT $值,以指定控制台输出。
CONIN $能解决到控制台输入缓冲区,即使SetStdHandle函数重定向标准输入句柄。要获得标准输入处理,使用GetStdHandle函数。
CONOUT $能解决到活动屏幕缓冲区,即使SetStdHandle重定向标准输出句柄。为了让标准输出处理,使用GetStdHandle。
dwDesiredAccessGENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.
dwShareModeWhen opening CONIN$, specify FILE_SHARE_READ. When opening CONOUT$, specify FILE_SHARE_WRITE.
If the calling process inherits the console, or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.
lpSecurityAttributesIf you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.
dwCreationDispositionYou should specify OPEN_EXISTING when using CreateFile to open the console.
dwFlagsAndAttributesIgnored.
hTemplateFileIgnored.
The following table shows various settings of dwDesiredAccess and lpFileName.
lpFileNamedwDesiredAccessResult
CONGENERIC_READOpens console for input.
CONGENERIC_WRITEOpens console for output.
CONGENERIC_READ | GENERIC_WRITECauses CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.
邮筒
If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function.
For more information, see Mailslots .
管道
If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required, but after it is opened, the named pipe instance cannot be opened by another client. The access that is specified when a pipe is opened must be compatible with the access that is specified in the dwOpenMode parameter of the CreateNamedPipe function.
If the CreateNamedPipe function was not successfully called on the server prior to this operation, a pipe will not exist and CreateFile will fail with ERROR_FILE_NOT_FOUND.
If there is at least one active pipe instance but there are no available listener pipes on the server, which means all pipe instances are currently connected, CreateFile fails with ERROR_PIPE_BUSY.
For more information, see Pipes .
实例
Example file operations are shown in Opening a File for Reading or Writing .
Physical device I/O is demonstrated in Calling DeviceIoControl .
A tape backup code snippet can found at Creating a Backup Application .
要求:
最低支持:client-Windows 2000专业版
最低支持server-Windows 2000服务器
HeaderWinBase.h(头文件:winuser.h)
LibraryKernel32.lib
DLLKernel32.dll
Unicode and ANSI namesCreateFileW (Unicode) and CreateFileA (ANSI)
参见
Overview Topics
About Directory Management
About Volume Management
备份
通信
Creating, Deleting, and Maintaining Files
Device Input and Output Control (IOCTL)
文件压缩和解压
文件加密
文件管理函数
File Security and Access Rights
File Streams
I/O Completion Ports
I/O Concepts
邮筒
Obtaining and Setting File Information
管道
运行具有特权

函数
CloseHandle
CreateDirectory
CreateDirectoryEx
CreateFileTransacted
CreateMailSlot
CreateNamedPipe
的DeleteFile
的DeviceIoControl
GetLastError函数
ReadFile
ReadFileEx
SetFileAttributes
WriteFile
WriteFileEx
如果有任何问题和意见,请发送给微软(wsddocfb@microsoft.com)
生成日期:2009年9月3日
==英文原文==CreateFile Function
Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified.
To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the CreateFileTransacted function.
Syntax
C++
HANDLE WINAPI CreateFile(
__in LPCTSTR lpFileName,
__in DWORD dwDesiredAccess,
__in DWORD dwShareMode,
__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
__in DWORD dwCreationDisposition,
__in DWORD dwFlagsAndAttributes,
__in_opt HANDLE hTemplateFile
);
Parameters
lpFileName [in]
The name of the file or device to be created or opened.
In the ANSI version of this function, the name is limited to MAX_PATH 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, see Defining an MS-DOS Device Name .
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 .
dwDesiredAccess [in]
The requested access to the file or device, which can be summarized as read, write, both or neither (zero).
The most commonly used values are GENERIC_READ, GENERIC_WRITE, or both (GENERIC_READ | GENERIC_WRITE). For more information, see Generic Access Rights and File Security and Access Rights .
If this parameter is zero, the application can query certain metadata such as file, directory, or device attributes without accessing that file or device, even if GENERIC_READ access would have been denied.
You cannot request an access mode that conflicts with the sharing mode that is specified by the dwShareMode parameter in an open request that already has an open handle.
For more information, see the Remarks section of this topic and Creating and Opening Files .
dwShareMode [in]
The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none (refer to the following table). Access requests to attributes or extended attributes are not affected by this flag.
If this parameter is zero and CreateFile succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed. For more information, see the Remarks section.
You cannot request a sharing mode that conflicts with the access mode that is specified in an existing request that has an open handle. CreateFile would fail and the GetLastError function would return ERROR_SHARING_VIOLATION.
To enable a process to share a file or device while another process has the file or device open, use a compatible combination of one or more of the following values. For more information about valid combinations of this parameter with the dwDesiredAccess parameter, see Creating and Opening Files .
Note The sharing options for each open handle remain in effect until that handle is closed, regardless of process context.
ValueMeaning
0
0x00000000Prevents other processes from opening a file or device if they request delete, read, or write access.
FILE_SHARE_DELETE
0x00000004Enables subsequent open operations on a file or device to request delete access.
Otherwise, other processes cannot open the file or device if they request delete access.
If this flag is not specified, but the file or device has been opened for delete access, the function fails.
Note Delete access allows both delete and rename operations.
FILE_SHARE_READ
0x00000001Enables subsequent open operations on a file or device to request read access.
Otherwise, other processes cannot open the file or device if they request read access.
If this flag is not specified, but the file or device has been opened for read access, the function fails.
FILE_SHARE_WRITE
0x00000002Enables subsequent open operations on a file or device to request write access.
Otherwise, other processes cannot open the file or device if they request write access.
If this flag is not specified, but the file or device has been opened for write access or has a file mapping with write access, the function fails.

lpSecurityAttributes [in, optional]
A pointer to a SECURITY_ATTRIBUTES structure that contains two separate but related data members: an optional security descriptor, and a Boolean value that determines whether the returned handle can be inherited by child processes.
This parameter can be NULL.
If this parameter is NULL, the handle returned by CreateFile cannot be inherited by any child processes the application may create and the file or device associated with the returned handle gets a default security descriptor.
The lpSecurityDescriptor member of the structure specifies a SECURITY_DESCRIPTOR for a file or device. If this member is NULL, the file or device associated with the returned handle is assigned a default security descriptor.
CreateFile ignores the lpSecurityDescriptor member when opening an existing file or device, but continues to use the bInheritHandle member.
The bInheritHandle member of the structure specifies whether the returned handle can be inherited.
For more information, see the Remarks section.
dwCreationDisposition [in]
An action to take on a file or device that exists or does not exist.
For devices other than files, this parameter is usually set to OPEN_EXISTING.
For more information, see the Remarks section.
This parameter must be one of the following values, which cannot be combined:
ValueMeaning
CREATE_ALWAYS
2Creates a new file, always.
If the specified file exists and is writable, the function overwrites the file, the function succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183).
If the specified file does not exist and is a valid path, a new file is created, the function succeeds, and the last-error code is set to zero.
For more information, see the Remarks section of this topic.
CREATE_NEW
1Creates a new file, only if it does not already exist.
If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
If the specified file does not exist and is a valid path to a writable location, a new file is created.
OPEN_ALWAYS
4Opens a file, always.
If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.
OPEN_EXISTING
3Opens a file or device, only if it exists.
If the specified file or device does not exist, the function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
For more information about devices, see the Remarks section.
TRUNCATE_EXISTING
5Opens a file and truncates it so that its size is zero bytes, only if it exists.
If the specified file does not exist, the function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
The calling process must open the file with the GENERIC_WRITE bit set as part of the dwDesiredAccess parameter.

dwFlagsAndAttributes [in]
The file or device attributes and flags, FILE_ATTRIBUTE_NORMAL being the most common default value for files.
This parameter can include any combination of the available file attributes (FILE_ATTRIBUTE_*). All other file attributes override FILE_ATTRIBUTE_NORMAL.
This parameter can also contain combinations of flags (FILE_FLAG_*) for control of file or device caching behavior, access modes, and other special-purpose flags. These combine with any FILE_ATTRIBUTE_* values.
This parameter can also contain Security Quality of Service information by specifying the SECURITY_SQOS_PRESENT flag. Additional SQOS-related flags information is presented in the table following the attributes and flags tables.
Note When CreateFile opens an existing file, it generally combines the file flags with the file attributes of the existing file, and ignores any file attributes supplied as part of dwFlagsAndAttributes. Special cases are detailed in Creating and Opening Files .
Some of the following file attributes and flags may only apply to files and not necessarily all other types of devices that CreateFile can open. For additional information, see the Remarks section of this topic and Creating and Opening Files .
For more advanced access to file attributes, see SetFileAttributes . For a complete list of all file attributes with their values and descriptions, see File Attributes .
AttributeMeaning
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.

FlagMeaning
FILE_FLAG_BACKUP_SEMANTICS
0x02000000The 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.
FILE_FLAG_DELETE_ON_CLOSE
0x04000000The 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
0x20000000The 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_OPEN_NO_RECALL
0x00100000The 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
0x00200000Normal 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
0x40000000The file or device is being opened or created for asynchronous 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
0x0100000Access 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
0x10000000Access 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
0x08000000Access 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
0x80000000Write 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.

The dwFlagsAndAttributes parameter can also specify Security Quality of Service information. For more information, see Impersonation Levels . When the calling application specifies the SECURITY_SQOS_PRESENT flag as part of dwFlagsAndAttributes, it can also contain one or more of the following values.
Security flagMeaning
SECURITY_ANONYMOUSImpersonates a client at the Anonymous impersonation level.
SECURITY_CONTEXT_TRACKINGThe security tracking mode is dynamic. If this flag is not specified, the security tracking mode is static.
SECURITY_DELEGATIONImpersonates a client at the Delegation impersonation level.
SECURITY_EFFECTIVE_ONLYOnly 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_IDENTIFICATIONImpersonates a client at the Identification impersonation level.
SECURITY_IMPERSONATIONImpersonate a client at the impersonation level. This is the default behavior if no other flags are specified along with the SECURITY_SQOS_PRESENT flag.

hTemplateFile [in, optional]
A valid 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 this parameter.
When opening a new encrypted file, the file inherits the discretionary access control list from its parent directory. For additional information, see File Encryption
Return Value
If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.
If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError .
Remarks
CreateFile was originally developed specifically for file interaction but has since been expanded and enhanced to include most other types of I/O devices and mechanisms available to Windows developers. This section attempts to cover the varied issues developers may experience when using CreateFile in different contexts and with different I/O types. The text attempts to use the word file only when referring specifically to data stored in an actual file on a file system. However, some uses of file may be referring more generally to an I/O object that supports file-like mechanisms. This liberal use of the term file is particularly prevalent in constant names and parameter names because of the previously mentioned historical reasons.
When an application is finished using the object handle returned by CreateFile, use the CloseHandle function to close the handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and committing data to disk. Specifics are noted within this topic as appropriate.
Windows Server 2003 and Windows XP/2000: A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote computer when the value of the dwDesiredAccess parameter is the DELETE access flag OR'ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE. To avoid the sharing violation in this scenario, open the remote file or directory with the DELETE access right only, or call DeleteFile without first opening the file or directory for deletion.
Some file systems, such as the NTFS file system, support compression or encryption for individual files and directories. On volumes that have a mounted file system with this support, a new file inherits the compression and encryption attributes of its directory.
You cannot use CreateFile to control compression, decompression, or decryption on a file or directory. For more information, see Creating and Opening Files , File Compression and Decompression , and File Encryption .
Windows Server 2003 and Windows XP/2000: For backward compatibility purposes, CreateFile does not apply inheritance rules when you specify a security descriptor in lpSecurityAttributes. To support inheritance, functions that later query the security descriptor of this file may heuristically determine and report that inheritance is in effect. For more information, see Automatic Propagation of Inheritable ACEs .
As stated previously, if the lpSecurityAttributes parameter is NULL, the handle returned by CreateFile cannot be inherited by any child processes your application may create. The following information regarding this parameter also applies:
If the bInheritHandle member variable is not FALSE, which is any non-zero value, then the handle can be inherited. Therefore it is critical this structure member be properly initialized to FALSE if you do not intend the handle to be inheritable.
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 the lpSecurityDescriptor member to have an effect on them, which can be determined by using GetVolumeInformation .
Symbolic Link Behavior
If the call to this function creates a file, there is no change in behavior. Also, consider the following information regarding FILE_FLAG_OPEN_REPARSE_POINT:
If FILE_FLAG_OPEN_REPARSE_POINT is specified:
If an existing file is opened and it is a symbolic link, the handle returned is a handle to the symbolic link.
If TRUNCATE_EXISTING or FILE_FLAG_DELETE_ON_CLOSE are specified, the file affected is a symbolic link.
If FILE_FLAG_OPEN_REPARSE_POINT is not specified:
If an existing file is opened and it is a symbolic link, the handle returned is a handle to the target.
If CREATE_ALWAYS, TRUNCATE_EXISTING, or FILE_FLAG_DELETE_ON_CLOSE are specified, the file affected is the target.
Caching Behavior
Several of the possible values for the dwFlagsAndAttributes parameter are used by CreateFile to control or affect how the data associated with the handle is cached by the system. They are:
FILE_FLAG_NO_BUFFERING
FILE_FLAG_RANDOM_ACCESS
FILE_FLAG_SEQUENTIAL_SCAN
FILE_FLAG_WRITE_THROUGH
FILE_ATTRIBUTE_TEMPORARY
If none of these flags is specified, the system uses a default general-purpose caching scheme. Otherwise, the system caching behaves as specified for each flag.
Some of these flags should not be combined. For instance, combining FILE_FLAG_RANDOM_ACCESS with FILE_FLAG_SEQUENTIAL_SCAN is self-defeating.
Specifying the FILE_FLAG_SEQUENTIAL_SCAN 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 forward over small ranges of bytes. If an application moves the file pointer for random access, optimum caching performance most likely will not occur. However, correct operation is still guaranteed.
The flags FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING are independent and may be combined.
If FILE_FLAG_WRITE_THROUGH is used but 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_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING are both specified, so that system caching is not in effect, then the data is immediately flushed to disk without going through the Windows system cache. The operating system also requests a write-through of the hard disk's local hardware cache to persistent media.
Note Not all hard disk hardware supports this write-through capability.
Proper use of the FILE_FLAG_NO_BUFFERING flag requires special application considerations. For more information, see File Buffering .
A write-through request via FILE_FLAG_WRITE_THROUGH also causes NTFS to flush any metadata changes, such as a time stamp update or a rename operation, that result from processing the request. For this reason, the FILE_FLAG_WRITE_THROUGH flag is often used with the FILE_FLAG_NO_BUFFERING flag as a replacement for calling the FlushFileBuffers function after each write, which can cause unnecessary performance penalties. Using these flags together avoids those penalties. For general information about the caching of files and metadata, see File Caching .
When FILE_FLAG_NO_BUFFERING is combined with FILE_FLAG_OVERLAPPED, the flags give 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 (for example, when creating an empty file). To ensure that the metadata is flushed to disk, use the FlushFileBuffers function.
Specifying the FILE_ATTRIBUTE_TEMPORARY attribute causes file systems to 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. Although it doesn't directly control data caching in the same way as the previously mentioned flags, the FILE_ATTRIBUTE_TEMPORARY attribute does tell the system to hold as much as possible in the system cache without writing and therefore may be of concern for certain applications.
Files
If you rename or delete a file and then restore it shortly afterward, the system searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.
If you call CreateFile on a file that is pending deletion as a result of a previous call to DeleteFile, the function fails. The operating system delays file deletion until all handles to the file are closed. GetLastError returns ERROR_ACCESS_DENIED.
The dwDesiredAccess parameter can be zero, allowing the application to query file attributes without accessing the file if the application is running with adequate security settings. This is useful to test for the existence of a file without opening it for read and/or write access, or to obtain other statistics about the file or directory. See Obtaining and Setting File Information and GetFileInformationByHandle
Windows Server 2003 and Windows XP/2000: If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute. To avoid the error, specify the same attributes as the existing file.
When an application creates a file across a network, it is better to use GENERIC_READ | GENERIC_WRITE for dwDesiredAccess than to use GENERIC_WRITE alone. The resulting code is faster, because the redirector can use the cache manager and send fewer SMBs with more data. This combination also avoids an issue where writing to a file across a network can occasionally return ERROR_ACCESS_DENIED.
For more information, see Creating and Opening Files .
Synchronous and Asynchronous I/O Handles
CreateFile provides for creating a file or device handle that is either synchronous or asynchronous. A synchronous handle behaves such that I/O function calls using that handle are blocked until they complete, while an asynchronous file handle makes it possible for the system to return immediately from I/O function calls, whether they completed the I/O operation or not. As stated previously, this synchronous versus asynchronous behavior is determined by specifying FILE_FLAG_OVERLAPPED within the dwFlagsAndAttributes parameter. There are several complexities and potential pitfalls when using asynchronous I/O; for more information, see Synchronous and Asynchronous I/O .
File Streams
On NTFS file systems, you can use CreateFile to create separate streams within a file. For more information, see File Streams .
Directories
An application cannot create a directory by using CreateFile, therefore only the OPEN_EXISTING value is valid for dwCreationDisposition for this use case. To create a directory, the application must call CreateDirectory or CreateDirectoryEx .
To open a directory using CreateFile, specify the FILE_FLAG_BACKUP_SEMANTICS flag as part of dwFlagsAndAttributes. Appropriate security checks still apply when this flag is used without SE_BACKUP_NAME and SE_RESTORE_NAME privileges.
When using CreateFile to open a directory during defragmentation of a FAT or FAT32 file system volume, do not specify the MAXIMUM_ALLOWED access right. Access to the directory is denied if this is done. Specify the GENERIC_READ access right instead.
For more information, see About Directory Management
Physical Disks and Volumes
Direct access to the disk or to a volume is restricted. For more information, see "Changes to the file system and to the storage stack to restrict direct disk access and direct volume access in Windows Vista and in Windows Server 2008" in the Help and Support Knowledge Base at http://support.microsoft.com/kb/942448 .
Windows Server 2003 and Windows XP/2000: Direct access to the disk or to a volume is not restricted in this manner.
You can use the CreateFile function to open a physical disk drive or a volume, which returns a direct access storage device (DASD) handle that can be used with the DeviceIoControl function. This enables you to access the disk or volume directly, for example such disk metadata as the partition table. However, this type of access also exposes the disk drive or volume to potential data loss, because an incorrect write to a disk using this mechanism could make its contents inaccessible to the operating system. To ensure data integrity, be sure to become familiar with DeviceIoControl and how other APIs behave differently with a direct access handle as opposed to a file system handle.
The following requirements must be met for such a call to succeed:
The caller must have administrative privileges. For more information, see Running with Special Privileges .
The dwCreationDisposition parameter must have the OPEN_EXISTING flag.
When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag.
Note The dwDesiredAccess parameter can be zero, allowing the application to query 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 disk in a drive, for instance. It can also be used for reading statistics without requiring higher-level data read/write permission.
When opening a physical drive x, the lpFileName string should be the following form: \\\\.\\PhysicalDriveX. Hard disk numbers start at zero. The following table shows some examples of physical drive strings.
StringMeaning
\\\\.\\PhysicalDrive0Opens the first physical drive.
\\\\.\\PhysicalDrive2Opens the third physical drive.

To obtain the physical drive identifier for a volume, open a handle to the volume and call the DeviceIoControl function with IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS . This control code returns the disk number and offset for each of the volume's one or more extents; a volume can span multiple physical disks.
For an example of opening a physical drive, see Calling DeviceIoControl .
When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive), the lpFileName string should be the following form: \\\\.\\X:. Do not use a trailing backslash (\\), which indicates the root directory of a drive. The following table shows some examples of drive strings.
StringMeaning
\\\\.\\A:Opens floppy disk drive A.
\\\\.\\C:Opens the C: volume.
\\\\.\\C:\\Opens the file system of the C: volume.

You can also open a volume by referring to its volume name. For more information, see Naming a Volume .
A volume contains one or more mounted file systems. Volume handles can be opened as noncached at the discretion of the particular file system, even when the noncached option is not specified in CreateFile. You should assume that all Microsoft file systems open volume handles as noncached. The restrictions on noncached I/O for files also apply to volumes.
A file system may or may not require buffer alignment even though the data is noncached. However, if the noncached option is specified when opening a volume, buffer alignment is enforced regardless of the file system on the volume. It is recommended on all file systems that you open volume handles as noncached, and follow the noncached I/O restrictions.
Note To read or write to the last few sectors of the volume, you must call DeviceIoControl and specify FSCTL_ALLOW_EXTENDED_DASD_IO . This signals the file system driver not to perform any I/O boundary checks on partition read or write calls. Instead, boundary checks are performed by the device driver.
Changer Device
The IOCTL_CHANGER_* control codes for DeviceIoControl accept a handle to a changer device. To open a changer device, use a file name of the following form: \\\\.\\Changerx where x is a number that indicates which device to open, starting with zero. To open changer device zero in an application that is written in C or C++, use the following file name: "\\\\\\\\.\\\\Changer0".
Tape Drives
You can open tape drives by using a file name of the following form: \\\\.\\TAPEx where x is a number that indicates which drive to open, starting with tape drive zero. To open tape drive zero in an application that is written in C or C++, use the following file name: "\\\\\\\\.\\\\TAPE0".
For more information, see Backup .
Communications Resources
The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be zero (exclusive access), and the hTemplateFile parameter must be NULL. Read, write, or read/write access can be specified, and the handle can be opened for overlapped I/O.
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.
For more information about communications, see Communications .
Consoles
The CreateFile function can create a handle to console input (CONIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the CreateFile parameters as follows.
ParametersValue
lpFileNameUse the CONIN$ value to specify console input.
Use the CONOUT$ value to specify console output.
CONIN$ gets a handle to the console input buffer, even if the SetStdHandle function redirects the standard input handle. To get the standard input handle, use the GetStdHandle function.
CONOUT$ gets a handle to the active screen buffer, even if SetStdHandle redirects the standard output handle. To get the standard output handle, use GetStdHandle.
dwDesiredAccessGENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.
dwShareModeWhen opening CONIN$, specify FILE_SHARE_READ. When opening CONOUT$, specify FILE_SHARE_WRITE.
If the calling process inherits the console, or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.
lpSecurityAttributesIf you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.
dwCreationDispositionYou should specify OPEN_EXISTING when using CreateFile to open the console.
dwFlagsAndAttributesIgnored.
hTemplateFileIgnored.

The following table shows various settings of dwDesiredAccess and lpFileName.
lpFileNamedwDesiredAccessResult
CONGENERIC_READOpens console for input.
CONGENERIC_WRITEOpens console for output.
CONGENERIC_READ | GENERIC_WRITECauses CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.

Mailslots
If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function.
For more information, see Mailslots .
Pipes
If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required, but after it is opened, the named pipe instance cannot be opened by another client. The access that is specified when a pipe is opened must be compatible with the access that is specified in the dwOpenMode parameter of the CreateNamedPipe function.
If the CreateNamedPipe function was not successfully called on the server prior to this operation, a pipe will not exist and CreateFile will fail with ERROR_FILE_NOT_FOUND.
If there is at least one active pipe instance but there are no available listener pipes on the server, which means all pipe instances are currently connected, CreateFile fails with ERROR_PIPE_BUSY.
For more information, see Pipes .
Examples
Example file operations are shown in Opening a File for Reading or Writing .
Physical device I/O is demonstrated in Calling DeviceIoControl .
A tape backup code snippet can found at Creating a Backup Application .
Requirements
Minimum supported clientWindows 2000 Professional
Minimum supported serverWindows 2000 Server
HeaderWinBase.h (include Windows.h)
LibraryKernel32.lib
DLLKernel32.dll
Unicode and ANSI namesCreateFileW (Unicode) and CreateFileA (ANSI)
See Also
Overview Topics
About Directory Management
About Volume Management
Backup
Communications
Creating, Deleting, and Maintaining Files
Device Input and Output Control (IOCTL)
File Compression and Decompression
File Encryption
File Management Functions
File Security and Access Rights
File Streams
I/O Completion Ports
I/O Concepts
Mailslots
Obtaining and Setting File Information
Pipes
Running with Special Privileges

Functions
CloseHandle
CreateDirectory
CreateDirectoryEx
CreateFileTransacted
CreateMailSlot
CreateNamedPipe
DeleteFile
DeviceIoControl
GetLastError
ReadFile
ReadFileEx
SetFileAttributes
WriteFile
WriteFileEx
Send comments about this topic to Microsoft
Build date: 9/3/2009
==原始网址==http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\n
随便看

 

windows api函数参考手册包含2258条windows api函数文档,详细介绍nodejs、java、rust调用windows api的方法技巧,是学习windows api编程的入门中文文档。

 

Copyright © 2004-2023 Winrtm.com All Rights Reserved
京ICP备2021023879号-40 更新时间:2024/10/6 13:20:30