Thomson-Blog ( 学习,学习,再学习;努力,努力,再努力。)
在学习的路上不断成长,成功之路就在脚下。

文件操作是应用程序最为基本的功能之一,在Linux下,采用申请虚拟内存的方法,可以申请到2g以上的内存,但是能操过3g-程序本身所占内存大小。在Windows2000中,一般能申请1g以上的内存,不能超过2g-程序本身所占内存大小。经过特殊配置,windows2000可以申请到与linux相同的数量的内存。不过具体能够申请多少内存,还要开虚存空间中最大的连续地址空间是多大。同时,能够申请到的内存数量不受系统ram的限制,理论上每个进程都有4G(如果打开了EMT64,可以有64G)内存空间,但是一般操作系统要占用高端的1g或2g。内存映射文件是所有支持页式内存管理的操作系统必备的功能。

在linux中,内存映像文件的系统调用有如下几个(没有给全:)

mmap(),该函数将一个磁盘文件映射到内存中,其原形如下:
      void   *mmap(   void   *start,   size_t   length,   int   prot,   int   flags,   int   fd,   off_t   offset   )
被影射的文件由被打开的文件描述符fd来决定,映射的内容从文件中偏移量为offset的地方开始,映射的内存空间从start开始,映射的长度由length来设定。映射的内存空间拥有保护措施,其值如下:
        PROT_NONE         不允许访问
        PROT_READ         被映像内存区可读
        PROT_WRITE       被映像内存区可写
        PROT_EXEC         被映像内存区可执行
映射的属性如下:
        MAP_ANONYMOUS   创建匿名映像,忽略fd
        MAP_FIXED           当地址无效或正在被使用时失败
        MAP_PRIVATE       被映射的内存区的写是私有的
        MAP_SHARE           被映射的内存区的写也被拷贝到文件中
        MAP_DENYWRITE   不允许正常的写文件
        MAP_GROWSDOWN   被映射的内存区是向下扩张的
        MAP_LOCKEO         锁住内存页
        文件描述符是一个文件句柄,是通过调用系统调用open()而获得的。参数offset一般被设置为0,这样,整个文件都能被映射到内存中。
        用于映射的内存区必须是私有的(使用MAP_PRIVATE)或共享的(使用MAP_SHARE)。其它为可选值。对于私有映射,对文件的修改是记录在进程的私有内存区中,因此它不能在底层文件中被反映出来,也不能被别的进程访问。对于共享映射,在内存中所作的任何修改都能立即被映射相同文件的其它进程所察觉。
        在不需要文件写回磁盘时可以使用MAP_DENYWRITE。要创建匿名映射可以使用MAP_ANONYMOUS,它并不映射磁盘文件,仅仅是分配进程单独使用到的内存空间,其作用有点像函数malloc()。使用MAP_FIXED标记可以让内核把文件映射到指定的地址。如果该地址不可用或已被占用,函数mmap()失败。如果没有使用MAP_FIXED标记而该地址也不可用,那么内核就将尝试用别的内存区来代替。使用MAP_LOCKED标记可以让有root用户权限的进程锁住该内存区,使其内容不会被置换到磁盘中去。为了防止未经授权的进程锁住内存以导致系统的瘫痪,普通用户程序不能使用MAP_LOCKED标记。
        内存映射文件被使用完之后应该调用函数munmap()来撤销影射,并把内存交还给操作系统。其函数原形为:
        int   munmap(   void   *start,   size_t   length   );
        函数的第一个参数是要撤销映射的内存空间的起始地址,第二个参数是被撤销的内存空间的大小。内存空间被撤销映射之后,任何start的访问都将引起段错误。在进程结束时,所有的内存映像都被撤销。该函数在正常时返回0,失败时返回-1,并设置errno。
        函数msync()把映射文件写入磁盘,其函数原形为:
        int   msync(   const   void   *start,   size_t   length,   int   flags   );
        使用该函数的作用是更新磁盘文件的内容。要刷新到磁盘上去的从地址start开始,长度为length字节。标记flags是下列值的位或:
        MS_ASYNC             调度一个写操作并返回
        MS_SYNC               在msync()函数返回前文成写操作
        MS_INVALIDATE   让映射到相同文件的映射无效,以便让它们被更新为新的数据。

上述三个系统调用足够解决文件复制的问题了,这会比通常的操作快许多。

在Windows系统中,Win32 API和MFC均提供有支持文件处理的函数和类。一般来说,这些函数可以满足大多数场合的要求,但是对于某些特殊应用领域所需要的动辄几十GB、几百GB、乃至几TB的海量存储,再以通常的文件处理方法进行处理显然是行不通的。目前,对于上述这种大文件的操作一般是以内存映射文件的方式来加以处理的。
  内存映射文件与虚拟内存有些类似,通过内存映射文件可以保留一个地址空间的区域,同时将物理存储器提交给此区域,只是内存文件映射的物理存储器来自一个已经存在于磁盘上的文件,而非系统的页文件,而且在对该文件进行操作之前必须首先对文件进行映射,就如同将整个文件从磁盘加载到内存。由此可以看出,使用内存映射文件处理存储于磁盘上的文件时,将不必再对文件执行I/O操作,这意味着在对文件进行处理时将不必再为文件申请并分配缓存,所有的文件缓存操作均由系统直接管理,由于取消了将文件数据加载到内存、数据从内存到文件的回写以及释放内存块等步骤,使得内存映射文件在处理大数据量的文件时能起到相当重要的作用。另外,实际工程中的系统往往需要在多个进程之间共享数据,如果数据量小,处理方法是灵活多变的,如果共享数据容量巨大,那么就需要借助于内存映射文件来进行。实际上,内存映射文件正是解决本地多个进程间数据共享的最有效方法。
  首先要通过CreateFile()函数来创建或打开一个文件内核对象,这个对象标识了磁盘上将要用作内存映射文件的文件。在用CreateFile()将文件映像在物理存储器的位置通告给操作系统后,只指定了映像文件的路径,映像的长度还没有指定。为了指定文件映射对象需要多大的物理存储空间还需要通过CreateFileMapping()函数来创建一个文件映射内核对象以告诉系统文件的尺寸以及访问文件的方式。
  CreateFileMapping()在创建了文件映射对象后,还必须为文件数据保留一个地址空间区域,并把文件数据作为映射到该区域的物理存储器进行提交。由MapViewOfFile()函数负责通过系统的管理而将文件映射对象的全部或部分映射到进程地址空间,实际上相当于加载文件中指定的数据到内存中。此时,对内存映射文件的使用和处理同通常加载到内存中的文件数据的处理方式基本一样,在完成了对内存映射文件的使用时,还要通过一系列的操作完成对其的清除和使用过资源的释放。这部分相对比较简单,可以通过UnmapViewOfFile()完成从进程的地址空间撤消文件数据的映像、通过CloseHandle()关闭前面创建的文件映射对象和文件对象。
  实际上操作文件映射对象就相当于操作VC++文件读写方式下的文件内部指针。
  而在某些特殊行业,经常要面对十几GB乃至几十GB容量的巨型文件,而一个32位进程所拥有的虚拟地址空间只有232 = 4GB,显然不能一次将文件映像全部映射进来。对于这种情况只能依次将大文件的各个部分映射到进程中的一个较小的地址空间。这需要对上面的一般流程进行适当的更改:
  1)映射从文件开头的映像;
  2)对该映像进行访问;
  3)取消此映像;
  4)映射一个从文件中的一个更深的位移开始的新映像;
  5)重复步骤2,直到访问完全部的文件数据。
示例代码:
  在本例中,首先通过GetFileSize()得到被处理文件长度(64位)的高32位和低32位值。然后在映射过程中设定每次映射的块大小为1000倍的分配粒度(系统的数据分块大小),如果文件长度小于1000倍的分配粒度时则将块大小设置为文件的实际长度。在处理过程中由映射、访问、撤消映射构成了一个循环处理。其中,每处理完一个文件块后都通过关闭文件映射对象来对每个文件块进行整理。CreateFileMapping()、MapViewOfFile()等函数是专门用来进行内存文件映射处理用的。

        // 创建文件对象
 HANDLE hFile = ::CreateFile(strFile, GENERIC_READ,FILE_SHARE_READ, NULL,
  OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL);
 if (hFile == INVALID_HANDLE_VALUE)
 {
  TRACE("创建文件对象失败,错误代码:%d\r\n", GetLastError());
  return;
 }
 // 创建文件映射对象
 HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
 if (hFileMap == NULL)
 {
  TRACE("创建文件映射对象失败,错误代码:%d\r\n", GetLastError());  
  return;
 }
 // 得到系统分配粒度
 SYSTEM_INFO SysInfo;
 GetSystemInfo(&SysInfo);
 DWORD dwGran = SysInfo.dwAllocationGranularity;
 // 得到文件尺寸
 DWORD dwFileSizeHigh;
 __int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
 qwFileSize |= (((__int64)dwFileSizeHigh) << 32);///MSDN

 // 偏移地址
 __int64 qwFileOffset = 0;
 __int64 T_newmap = 900 * dwGran;
 // 块大小
 DWORD dwBlockBytes = 1000 * dwGran;//文件数据分段大小
 if (qwFileSize - qwFileOffset < dwBlockBytes)
  dwBlockBytes = (DWORD)qwFileSize;

 // 映射视图
 char *lpbMapAddress = (char *)MapViewOfFile(hFileMap,FILE_MAP_READ,
  (DWORD)(qwFileOffset >> 32), (DWORD)(qwFileOffset & 0xFFFFFFFF),dwBlockBytes);
 if (lpbMapAddress == NULL)
 {
  TRACE("映射文件映射失败,错误代码:%d ", GetLastError());
  return;
 } 
 // 关闭文件对象
 CloseHandle(hFile); 
 ///////////读文件数据
 while(qwFileOffset < qwFileSize)
 {
  /********************            读文件             ***************************/  
  //read_eh(&lpbMapAddress)读取已映射到内存的数据,并将文件指针作相应后移(lpbMapAddress++),返回指针偏移量
  qwFileOffset = qwFileOffset + read_eh(&lpbMapAddress); //修改偏移量
  if (qwFileOffset > T_newmap)
  {//当数据读到90%时,为防数据溢出,需要映射在其后的数据  T_newmap
   UnmapViewOfFile(lpbMapAddress);//释放当前映射
   if ((DWORD)(qwFileSize - T_newmap) < dwBlockBytes)
   dwBlockBytes = (DWORD)(qwFileSize - T_newmap);
   lpbMapAddress = (char *)MapViewOfFile(hFileMap,FILE_MAP_READ,
   (DWORD)(T_newmap >> 32), (DWORD)(T_newmap & 0xFFFFFFFF),dwBlockBytes);
   // 修正参数
   lpbMapAddress = lpbMapAddress + qwFileOffset - T_newmap;
   T_newmap =T_newmap  + 900 * dwGran;
   if (lpbMapAddress == NULL)
   {
    TRACE("映射文件映射失败,错误代码:%d ", GetLastError());
    return;
   }
  }
 }
 //释放最后数据块映射
 UnmapViewOfFile(lpbMapAddress);
 // 关闭文件映射对象句柄
 CloseHandle(hFileMap); 

异步磁盘 I/O 出现在 Windows NT、 Windows 2000 和 Windows XP 上同步

在 Microsoft Windows NT、 Windows 2000 和 Windows XP 上的文件 I/O 可以同步或异步。I/O 的默认行为是同步的: 一个 I/O 函数调用和返回 I/O 完成后。异步的 I/O 另一方面,允许立即,返回到调用方返回执行一个 I/O 函数,但 I/O 不假定为将来的某个时间之前完成。I/O 完成后,操作系统将通知调用方。或者,调用方可以通过使用操作系统的服务来确定未完成的 I/O 操作的状态。

异步 I/O 的优点是调用方都有时间来进行其他工作,或在 I/O 操作完成前发出更多的请求。术语 Overlapped I/O 经常用于异步 I/O 和不重叠的 I/O 的同步 I/O。本文使用术语异步和同步在 Windows NT 下的 I/O 操作。本文假定读者已在文件 I/O 功能 (如 CreateFile,ReadFile,WriteFile 某些熟悉。

经常,异步 I/O 操作行为只是为同步 I/O 本文讨论了更高版本的各节使同步完成 I/O 操作中的某些条件。因为 I/O 函数不返回 I/O 完成之前,调用方具有没有后台工作的时间。

与同步和异步 I/O 相关的几个函数。本文作为示例使用 ReadFile 和 WriteFile ; ReadFileEx 和 WriteFileEx 是很好的备选方案。尽管本文专门讨论磁盘 I/O,原则的许多可应用于其他类型的 I/O,例如串行 I/O 或网络 I/O。

: 由于 Windows 95 不支持异步 I/O 磁盘设备上 (尽管它不在其他类型的输入/输出设备上),其行为不涉及这篇文章。

设置异步 I/O

在打开文件时,必须在 $ CreateFile 中指定 FILE_FLAG_OVERLAPPED 标志。此标志允许异步执行对文件的 I/O 操作。下面是一个示例:
   HANDLE hFile;

   hFile = CreateFile(szFileName,
                      GENERIC_READ,
                      0,
                      NULL,
                      OPEN_EXISTING,
                      FILE_FLAG_NORMAL | FILE_FLAG_OVERLAPPED,
                      NULL);

   if (hFile == INVALID_HANDLE_VALUE)
      ErrorOpeningFile();
				
被编码为异步 I/O,因为系统有权进行同步,如果它需要的操作时,一定要小心。因此,它是最佳如果您编写该程序正确处理可能会同步或异步完成某个 I/O 操作。代码示例演示了此注意事项。

有很多事情,程序可以执行操作时,等待异步操作完成,如队列的其他操作或进行后台工作。例如对于下面的代码正确处理读取操作的重叠的和非重叠方式的完成。它不执行任何操作多个等待未完成的 I/O 完成:
   if (!ReadFile(hFile,
                 pDataBuf,
                 dwSizeOfBuffer,
                 &NumberOfBytesRead,
                 &osReadOperation )
   {
      if (GetLastError() != ERROR_IO_PENDING)
      {
         // Some other error occurred while reading the file.
         ErrorReadingFile();
         ExitProcess(0);
      }
      else
         // Operation has been queued and
         // will complete in the future.
         fOverlapped = TRUE;
   }
   else
      // Operation has completed immediately.
      fOverlapped = FALSE;

   if (fOverlapped)
   {
      // Wait for the operation to complete before continuing.
      // You could do some background work if you wanted to.
      if (GetOverlappedResult( hFile,
                               &osReadOperation,
                               &NumberOfBytesTransferred,
                               TRUE))
         ReadHasCompleted(NumberOfBytesTransferred);
      else
         // Operation has completed, but it failed.
         ErrorReadingFile();
   }
   else
      ReadHasCompleted(NumberOfBytesRead);
				
注意的和传递到 ReadFile NumberOfBytesRead 是不同于和 NumberOfBytesTransferred 传递到 GetOverlappedResult。如果某个操作已经进行异步,然后 GetOverlappedResult 用于确定实际它完成后,在操作中传输的字节数。在传递到 ReadFile NumberOfBytesRead 是毫无意义 (& i)。

如果手动,操作立即完成,然后和 NumberOfBytesRead 传递到 ReadFile 无效,读取的字节数。在这种情况下忽略传递到 ReadFile OVERLAPPED 结构 ; 不能将它与 GetOverlappedResult 或 WaitForSingleObject。

与异步操作的另一个需要说明的是不能使用一个 OVERLAPPED 结构其挂起的操作完成之前。也就如果三个未完成的 I/O 操作必须使用三个 OVERLAPPED 结构。如果您重复使用一个 OVERLAPPED 结构,您将收到不可预知的结果在 I/O 操作中,您可能会遇到数据损坏。 此外,才可以使用一个 OVERLAPPED 结构在第一次或更早版本的操作完成后您会重用它之前,必须正确地初始化因此没有左移过数据会影响新的操作。

相同类型的限制适用于在操作中使用的数据缓冲区。将数据缓冲区必须不能读取或写入其相应的 I/O 操作完成之前,读取或写入该缓冲区可能会导致错误和损坏的数据。

异步 I/O 静止似乎是同步

如果您执行了本文前面的说明但是,所有您 I/O 操作仍通常完成同步颁发,顺序和无 ReadFile 操作返回 FALSE GetLastError() 返回 ERROR_IO_PENDING,这意味着您没有任何后台工作的时间。这是为什么出现的?

有许多原因 I/O 操作完成同步即使您已编码的异步操作的原因:

压缩

一个异步操作的障碍物是 NTFS 压缩。文件系统驱动程序不将以异步方式进行压缩的文件访问 ; 而是所有操作只需都进行同步。这不适用于与类似于压缩或 $ PKZIP 实用程序压缩的文件。

NTFS 加密

类似于压缩,文件加密将导致将转换为同步的异步 I/O 系统驱动程序。如果文件解密,将异步 I/O 请求。

扩展文件

同步完成 I/O 操作的另一个原因是这些操作本身。在 Windows NT 上任何写操作以扩展其长度的文件将是同步的。

: 应用程序可以使前面提到的写操作异步通过使用 SetFileValidData 函数并再颁发一个 WriteFile 更改该文件的有效数据长度。

应用程序使用 SetFileValidData (这是 Windows XP 及更高版本中可用) 可以有效地扩展多文件而不需要的零填充它们会影响性能。

因为 NTFS 文件系统不会不为零的填充该数据,最大可达有效数据长度 (VDL) 由 SetFileValidData,该函数定义的具有安全隐患的文件可能分配了以前所占用的其他文件的群集。 因此,SetFileValidData 要求调用方具有新的 SeManageVolumePrivilege 启用 (默认状态下,这只分配给管理员)。 Microsoft 建议 isv 仔细考虑使用此函数的含义。

高速缓存

大多数 I/O 驱动程序 (磁盘、 通信,和其他人) 有特殊大小写的代码位置,如果 I/O 请求可以在"立即"完成,完成该操作和 ReadFile 或 WriteFile 函数将返回 TRUE。在所有的方法中这些类型的操作似乎是同步的。为磁盘设备通常,I/O 请求可以在完成数据缓存在内存中时,"立即"。

数据不在缓存中

缓存方案可以对您,但是,如果数据不在缓存中。在 Windows NT 缓存是在内部使用文件映射实现的。 在 Windows NT 中内存管理器不提供一种异步页容错机制来管理,缓存管理器所使用的文件映射。高速缓存管理器可以但是,验证请求的页面是否在内存中,因此,如果您发出的异步缓存的读取,并且页面不在内存中文件系统驱动程序假定您不希望您阻止的线程,并将由一个有限的辅助线程池处理该请求。控件仍等待读取您 ReadFile 调用之后返回到您的程序。

此工作正常的数量较少的请求,而是因为的工作线程池是那里限制 (当前三 16 MB 的系统上),将仍然只有几个请求排队,磁盘驱动程序以在特定时间。如果您发出大量 I/O 操作为不在缓存中的数据,在高速缓存管理器和内存管理器变为满负荷状态和您的请求进行同步。

此外根据是否访问的文件,按顺序或随机影响缓存管理器的行为。按顺序访问文件时,将最看到高速缓存的好处。FILE_FLAG_SEQUENTIAL_SCAN 标志 CreateFile 调用中的将优化了这种类型的访问权限的缓存。 但是,如果您访问以随机方式的文件,使用 FILE_FLAG_RANDOM_ACCESS 标志 CreateFile 中指示要优化的随机访问其行为,缓存管理器。

不使用缓存

FILE_FLAG_NO_BUFFERING 标志具有大多数的效果上的文件系统中有异步操作的行为。这是最好的方法保证实际上异步 I/O 请求。它指示文件系统根本不使用任何缓存机制。

警告: 没有使用此标志与数据缓冲区对齐方式和设备的扇区大小具有一些限制。请参阅函数参考 CreateFile 函数有关正确使用此标志的详细信息的文档中。

示例代码

以下文件是可从 Microsoft 下载中心下载:
Asynczip.exe (http://download.microsoft.com/download/platformsdk/sample/3/nt4/en-us/asynczip.exe)  
有关如何下载 Microsoft 支持文件的其他信息请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:
119591  (http://support.microsoft.com/kb/119591/EN-US/ ) 如何从联机服务获得 Microsoft 支持文件
Microsoft 扫描此文件的病毒。Microsoft 使用该文件已过帐的日期上获得的最新病毒检测软件。该文件存储在安全性得到增强的服务器,这有助于防止未经授权的情况下对其进行更改文件上。 与此文章关联的代码示例演示了使用的标志和讨论的函数。作为控制台应用程序在 Windows NT 上运行代码。 下面的命令行开关控制其行为:
   Asynchio
   Usage: asynchio [options]

   Options:
      /fFilePattern  Files to use for I/O.
      /s    Specifies synchronous operation.
      /n    Specifies that no buffering should be used
      /r    Use FILE_FLAG_RANDOM_ACCESS
      /l    Use FILE_FLAG_SEQUENTIAL_SCAN
      /o###    Issue ### operations
      /e    First read entire file, then issue smaller reads
      /?    Display this usage message.
				
示例: asynchio /f*.bmp/n
该程序的默认操作是异步的、 缓冲的操作。默认状态下,请求 500 I/O 操作。

真正全球测试结果

下面的代码示例从一些测试结果。数字量此处并不重要和不同计算机,但之间的数字相互比较关系照亮一般标志对性能的影响。

您可能会看到类似于以下内容的结果:
  • 测试 1
    Asynchronous, unbuffered I/O:  asynchio /f*.dat /n
    
       Operations completed out of the order in which they were requested.
       500 requests queued in 0.224264 seconds.
       500 requests completed in 4.982481 seconds.
    						
    此测试演示前面提到的程序快速颁发 500 的 I/O 请求,以及有很多时间来进行其他工作或发出更多的请求。
  • 测试 2
    Synchronous, unbuffered I/O: asynchio /f*.dat /s /n
    
       Operations completed in the order issued.
       500 requests queued and completed in 4.495806 seconds.
    						
    演示了此测试,该程序所用 4.495880 秒调用 ReadFile 完成它的操作,而测试 1 花费仅 0.224264 秒颁发相同的请求。在测试 2,没有对程序进行任何背景工作没有额外的时间。
  • 测试 3
    Asynchronous, buffered I/O: asynchio /f*.dat
    
       Operations completed in the order issued.
       500 requests issued and completed in 0.251670 seconds.
    						
    此测试演示同步高速缓存的性质。所有读取已发出,而且在 0.251670 秒内完成。也就是同步完成异步请求。当数据在缓存中时,此测试还演示,缓存管理器的高性能。
  • 测试 4
    Synchronous, buffered I/O: asynchio /f*.dat /s
    
       Operations completed in the order issued.
       500 requests and completed in 0.217011 seconds.
    						
    此测试演示作为测试 3 中相同的结果。请注意从缓存同步读取从缓存完成稍快于异步读取。当数据在缓存中时,此测试还演示,缓存管理器的高性能。

结束时

您可以决定哪种方法是最佳的因为这完全取决于类型、 大小,和您的程序执行的操作的数量。

默认文件访问,而不指定任何特殊的标记以 CreateFile 是同步和缓存的操作。

: 文件系统驱动程序不预测异步预读和异步惰性写入已修改的数据,因此您是否在此模式中获取某些自动的异步行为。尽管这不会使应用程序 [ASCII 146] s I/O 异步,它是理想的情况下为绝大多数的简单应用程序。

如果手动,您的应用程序不是简单的您可能不得不做一些分析和确定最佳的方法类似于本文前面所示的测试的性能监视。分析时所用的 ReadFile 或 WriteFile 函数,然后比较这次需要多长时间的实际完成的 I/O 操作是非常有用。如果大部分时间花费在实际颁发 I/O 在然后您 I/O 是正在同步完成。但是,如果颁发的 I/O 请求时间相对较小相比,为所需的 I/O 操作完成,然后您的操作被异步处理的时间。本文中前面提到的代码示例使用 QueryPerformanceCounter 函数来执行其自己的内部分析。

性能监视可帮助您确定您的程序如何有效地使用磁盘和高速缓存。跟踪任何缓存对象的性能计数器将指示,缓存管理器的性能。 跟踪物理磁盘或逻辑磁盘对象的性能计数器将指示磁盘系统的性能。

有几个有用中性能监视的实用程序 ; PerfMon 和 DiskPerf 是非常有用。收集的数据上的磁盘系统的性能系统都必须首先发出 diskperf-y 命令。发出命令后,您必须重新启动系统以启动数据收集。

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

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 Files, Paths, and Namespaces.

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, File Security and Access Rights, File Access Rights Constants, and ACCESS_MASK.

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
0x00000000

Prevents other processes from opening a file or device if they request delete, read, or write access.

FILE_SHARE_DELETE
0x00000004

Enables 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
0x00000001

Enables 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
0x00000002

Enables 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 bInheritHandlemember 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
2

Creates 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
1

Creates 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
4

Opens 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
3

Opens 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
5

Opens 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 (SQOS) 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 Attribute Constants.

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
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.

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_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.

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.

The dwFlagsAndAttributesparameter can also specify SQOS 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_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. 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 (0x00010000) 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 does not 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_EXISTINGflag.
  • When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITEflag.

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
"\\.\PhysicalDrive0" Opens the first physical drive.
"\\.\PhysicalDrive2" Opens 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

lpFileName

Use 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 GetStdHandlefunction.

CONOUT$ gets a handle to the active screen buffer, even if SetStdHandleredirects the standard output handle. To get the standard output handle, use GetStdHandle.

dwDesiredAccess

GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.

dwShareMode

When 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.

lpSecurityAttributes

If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.

dwCreationDisposition

You should specify OPEN_EXISTING when using CreateFile to open the console.

dwFlagsAndAttributes

Ignored.

hTemplateFile

Ignored.

The following table shows various settings of dwDesiredAccess and lpFileName.

lpFileNamedwDesiredAccessResult
"CON" GENERIC_READ Opens console for input.
"CON" GENERIC_WRITE Opens console for output.
"CON" GENERIC_READ | GENERIC_WRITE Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.

Mailslots

If CreateFileopens 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 dwOpenModeparameter 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 the following topics:

Physical device I/O is demonstrated in the following topics:

An example using named pipes is located at Named Pipe Client.

Working with a mailslot is shown in Writing to a Mailslot.

A tape backup code snippet can found at Creating a Backup Application.

Requirements

Minimum supported client

Windows 2000 Professional

Minimum supported server

Windows 2000 Server

Header

WinBase.h (include Windows.h)

Library

Kernel32.lib

DLL

Kernel32.dll

Unicode and ANSI names

CreateFileW (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
posted on 2011-02-14 09:19  Thomson-Blog  阅读(1873)  评论(0编辑  收藏  举报