Creating and Opening Files(创建与打开文件)

原文:http://msdn.microsoft.com/en-us/library/windows/desktop/aa363874%28v=vs.85%29.aspx


Creating and Opening Files

创建与打开文件

The CreateFile function can create a new file or open an existing file. You must specify the file name, creation instructions, and other attributes. When an application creates a new file, the operating system adds it to the specified directory.

CreateFile函数可以创建一个新文件或者打开一个已经存在的文件。 你必须指定文件名称,创建指令,以及其它属性。在应用程序创建新文件的时候,操作系统把它添加到指定的目录中去。

The operating system assigns a unique identifier, called a handle, to each file that is opened or created usingCreateFile. An application can use this handle with functions that read from, write to, and describe the file. It is valid until all references to that handle are closed. When an application starts, it inherits all open handles from the process that started it if the handles were created as inheritable.

操作系统为每一个使用CreateFile函数创建或者打开的文件分配一个唯一的标识符,称为Handle。应用程序可以使用这个handle来读,写,描述文件。在该handle的所有引用都被关闭之前,它都是有效的。当应用程序启动的时候,它将继承所有已经打开的handles 如果启动它的进程在将这些handles创建为可继承的。

An application should check the value of the handle returned by CreateFile before attempting to use the handle to access the file. If an error occurs, the handle value will beINVALID_HANDLE_VALUE and the application can use theGetLastError function for extended error information.

应用程序在使用由CreateFile函数返回的handle值存取文件时应当检查这些值。如果有错误发生,handle值被置为INVALID_HANDLE_VALUE(-1),应用程序可以调用GetLastError函数来获取扩展错误信息。

When an application uses CreateFile, it must use the dwDesiredAccess parameter to specify whether it intends to read from the file, write to the file, both read and write, or neither. This is known as requesting anaccess mode. The application must also use the dwCreationDisposition parameter to specify what action to take if the file already exists, known as thecreation disposition. For example, an application can callCreateFile withdwCreationDisposition set to CREATE_ALWAYS to always create a new file, even if a file of the same name already exists (thus overwriting the existing file). Whether this succeeds or not depends on factors such as the previous file's attributes and security settings (see the following sections for more information).

当应用程序在使用CreateFile的时候,它必须使用参数dwDesiredAccess来指定它是否要读文件,写文件,读写文件,或者两者都不。这叫做请求一种存取方式。如果文件已经存在,应用程序也必须使用dwCreationgDisposition参数来指定要采取什么操作,这叫做创建方式。例如,应用程序可以调用dwCreationDisposition参数被设置为CREATE_ALWAYS的CreateFile,来总是创建一个新文件,即使一个相同名字的文件已经存在(它会被覆盖)。调用是否成功取决于类似文件属性以及安全设置的因素。

An application also uses CreateFile to specify whether it wants to share the file for reading, writing, both, or neither. This is known as thesharing mode. An open file that is not shared (dwShareMode set to zero) cannot be opened again, either by the application that opened it or by another application, until its handle has been closed. This is also referred to as exclusive access.

应用程序也可以使用CreateFile来指定它是否想要共享文件读,写,读写,或者都不。这被称为共享方式。已经打开的非共享文件(dwShareMode被设置为0)不能再次被当前应用程序或者另一个应用程序打开,直到当前已经打开的文件句柄被关闭。这也被称作独占式存取。

When a process uses CreateFile to attempt to open a file that has already been opened in a sharing mode (dwShareMode set to a valid nonzero value), the system compares the requested access and sharing modes to those specified when the file was opened. If you specify an access or sharing mode that conflicts with the modes specified in the previous call,CreateFile fails.

当一个进程使用CreateFile来尝试打开一个已经被以共享方式打开(dwShareMode不等于0)的文件时,系统将请求的权限与共享方式同文件打开时的权限与共享方式做比较。如果你指定的权限或者共享方式与之前调用CreateFile时传入的对应的参数冲突,那CreateFile将失败。

The following table illustrates the valid combinations of two calls toCreateFile using various access modes and sharing modes (dwDesiredAccess,dwShareMode respectively).It does not matter in which order the CreateFile calls are made. However, any subsequent file I/O operations on each file handle will still be constrained by the current access and sharing modes associated with that particular file handle.

下面的表阐述了两个CreateFile调用不同存取模式与共享方式的的有效组合。CreateFile的调用顺序不重要。但是,每个文件句柄上任何后续的文件I/0操作都会被与那个特定文件句柄的当前的存取,共享方式限制。


First call to CreateFileValid second calls to CreateFile

GENERIC_READ, FILE_SHARE_READ

  • GENERIC_READ, FILE_SHARE_READ
  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_READ, FILE_SHARE_WRITE

  • GENERIC_WRITE, FILE_SHARE_READ
  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE

  • GENERIC_READ, FILE_SHARE_READ
  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_READ
  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ
  • GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |FILE_SHARE_WRITE

GENERIC_WRITE, FILE_SHARE_READ

  • GENERIC_READ, FILE_SHARE_WRITE
  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_WRITE, FILE_SHARE_WRITE

  • GENERIC_WRITE, FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE

  • GENERIC_READ, FILE_SHARE_WRITE
  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE
  • GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |FILE_SHARE_WRITE

GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ

  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE

  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE

GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |FILE_SHARE_WRITE

  • GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE
  • GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ |FILE_SHARE_WRITE

In addition to the standard file attributes, you can also specify security attributes by including a pointer to aSECURITY_ATTRIBUTES structure as the fourth parameter of CreateFile. However, the underlying file system must support security for this to have any effect (for example, the NTFS file system supports it but the various FAT file systems do not). For more information about security attributes, seeAccess Control.

An application creating a new file can supply an optional handle to a template file, from whichCreateFile takes file attributes and extended attributes for creation of the new file.

除了标准文件属性之外,你也可以通过包含一个SECURITY_ATTRIBUTES结构指针,并将它作为CreateFile的第四个参数指定安全属性来指定安全属性。但是,文件系统必须要支持它使它起作用(例如,NTFS文件系统支持它但是很多FAT文件系统不支持它)。关于安全属性的更多信息,请参考存取控制。

应用程序创建新文件的时候,可以提供一个可选的模板文件句柄,CreateFile从它那里获取文件属性以及扩展属性来创建新文件。

CreateFile Scenarios

CreateFile 场景

There are several fundamental scenarios for initiating access to a file using theCreateFile function. These are summarized as:

  • Creating a new file when a file with that name does not already exist.
  • Creating a new file even if a file of the same name already exists, clearing its data and starting empty.
  • Opening an existing file only if it exists, and only intact.
  • Opening an existing file only if it exists, truncating it to be empty.
  • Opening a file always: as-is if it exists, creating a new one if it does not exist.

These scenarios are controlled by the proper use of the dwCreationDisposition parameter. Below is a breakdown of how these scenarios map to values for this parameter and what happens when they are used.

使用CreateFile初始化存取方式有一些基本的场景,总结为:

  • 创建一个名字尚未不存在的新文件。
  • 创建一个新文件,即使同名文件已经存在,清除它的内容,使之为空。
  • 只在文件存在并完好的情况下打开一个已经存在的文件。
  • 打开一个已经存在的文件,并将它缩短为空。
  • 总是打开一个新文件:打开存在的,创建不存在的。

这些场景通过对参数dwCreationgDisposition的合适使用来控制。下面是是对 这些场景如何映射参数值以及当他们被使用的时候发生了什么的一个分类。

When creating or opening a new file when a file with that name does not already exist (dwCreationDisposition set to eitherCREATE_NEW, CREATE_ALWAYS, or OPEN_ALWAYS), theCreateFile function performs the following actions:

  • Combines the file attributes and flags specified by dwFlagsAndAttributes withFILE_ATTRIBUTE_ARCHIVE.
  • Sets the file length to zero.
  • Copies the extended attributes supplied by the template file to the new file if thehTemplateFile parameter is specified (this overrides all FILE_ATTRIBUTE_* flags specified earlier).
  • Sets the inherit flag specified by the bInheritHandle member and the security descriptor specified by thelpSecurityDescriptor member of the lpSecurityAttributes parameter (SECURITY_ATTRIBUTES structure), if supplied.

当创建或者打开一个新文件,并且该文件尚未存在的时候,CreateFile函数执行下列行为:

  • 将由dwFlagsAndAttributes指定的文件属性已经标志痛FILE_ATTRIBUTE_ARCHIVE组合。
  • 将文件长度设置为0.
  • 如果指定了hTemplateFile参数,就拷贝由模板文件提供的扩展属性到新文件。(这会覆盖所有之前指定的FILE_ATTRIBUTE_*标志)
  • 如果提供了lpSecurityAttributes参数,就设置由bInheritHandle指定的继承标志以及由lpSecurityAttributes成员lpSecurityDescriptor指定的安全描述符。


When creating a new file even if a file of the same name already exists (dwCreationDisposition set toCREATE_ALWAYS), the CreateFile function performs the following actions:

  • Checks current file attributes and security settings for write access, failing if denied.
  • Combines the file attributes and flags specified by dwFlagsAndAttributes withFILE_ATTRIBUTE_ARCHIVE and the existing file attributes.
  • Sets the file length to zero (that is, any data that was in the file is no longer available and the file is empty).
  • Copies the extended attributes supplied by the template file to the new file if thehTemplateFile parameter is specified (this overrides all FILE_ATTRIBUTE_* flags specified earlier).
  • Sets the inherit flag specified by the bInheritHandle member of thelpSecurityAttributes parameter (SECURITY_ATTRIBUTES structure) if supplied, but ignores thelpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure.
  • If otherwise successful (that is, CreateFile returns a valid handle), calling GetLastError will yield the code ERROR_ALREADY_EXISTS, even though for this particular use-case it is not actually an error as such (if you intended to create a "new" (empty) file in place of the existing one).

当创建一个新文件,即使已经存在同名文件时(dwCreationDisposition为CREATE_ALWAYS),CreateFile函数执行下列动作:

  • 检查当前与写权限相关的文件属性与安全设置,如果拒绝写入,则失败。
  • 将由dwFlagsAndAttributes指定的文件属性与标志同FILE_ATTRIBUTE_ARCHIVE以及存在的文件属性组合。
  • 将文件长度设置为0。
  • 如果指定了hTemplateFile参数,就拷贝由模板文件提供的扩展属性到新文件。(这会覆盖所有之前指定的FILE_ATTRIBUTE_*标志)
  • 如果提供了lpSecurityAttributes参数,则设置由lpSecurityAttributes参数的成员bInheritHandle指定的继承标志,但是忽略SECURITY_ATTRIBUTES结构的lpSecurityDescriptor成员。
  • 如果成功(即CreateFile返回一个有效句柄),调用GetLastError将返回ERROR_ALREADY_EXISTS代码,尽管对这个特殊的实例,像这样的错误并这不是真的错误。

When opening an existing file (dwCreationDisposition set to either OPEN_EXISTING, OPEN_ALWAYS, or TRUNCATE_EXISTING), theCreateFile function performs the following actions:

  • Checks current file attributes and security settings for requested access, failing if denied.
  • Combines the file flags (FILE_FLAG_*) specified by dwFlagsAndAttributes with existing file attributes, and ignores any file attributes (FILE_ATTRIBUTE_*) specified bydwFlagsAndAttributes.
  • Sets the file length to zero only if dwCreationDisposition is set toTRUNCATE_EXISTING, otherwise the current file length is maintained and the file is opened as-is.
  • Ignores the hTemplateFile parameter.
  • Sets the inherit flag specified by the bInheritHandle member of thelpSecurityAttributes parameter (SECURITY_ATTRIBUTES structure) if supplied, but ignores thelpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure.

当打开一个已经存在的文件时,CreateFile函数执行下列动作:

  • 检查当前与写权限相关的文件属性与安全设置,如果拒绝写入,则失败。
  • 将由dwFlagsAndAttributes指定的标志(FILE_FLAG_*)同存在的文件属性组合,同时忽略dwFlagsAndAttributes指定的文件属性(FILE_ATTRIBUTE_*)。
  • 如果dwCreateDisposition只被设置TRUNCATE_EXISTING,则设置文件长度为0,否则维持当前的文件长度,文件就是打开时的样子。
  • 忽略hTemplateFile参数。
  • 如果提供了lpSecurityAttributes参数,则设置由lpSecurityAttributes参数的成员bInheritHandle指定的继承标志,但是忽略SECURITY_ATTRIBUTES结构的lpSecurityDescriptor成员。

File Attributes and Directories

文件属性与目录

File attributes are part of the metadata associated with a file or directory, each with its own purpose and rules on how it can be set and changed. Some of these attributes apply only to files, and some only to directories. For example, theFILE_ATTRIBUTE_DIRECTORY attribute applies only to directories: It is used by the file system to determine whether an object on disk is a directory, but it cannot be changed for an existing file system object.

文件属性是与文件或者目录关联的元数据的一部分,每个都有它自己的目的以及设置与改变规则。有些属性只应用于文件,有些只应用于目录。例如,属性FILE_ATTRIBUTE_DIRECTORY属性只应用于目录:文件系统使用它们来决定磁盘上的对象是否是一个目录,但是它不能被改变为一个已经存在的文件系统对象。

Some file attributes can be set for a directory but have meaning only for files created in that directory, acting as default attributes. For example,FILE_ATTRIBUTE_COMPRESSED can be set on a directory object, but because the directory object itself contains no actual data, it is not truly compressed; however, directories marked with this attribute tell the file system to compress any new files added to that directory. Any file attribute that can be set on a directory and will also be set for new files added to that directory is referred to as aninherited attribute.

一些文件属性可用于设置目录,但这些属性值对创建在那个目录中的文件有意义,表现为默认属性。例如,FILE_ATTRIBUTE_COMPRESSED可以被设置在一个目录对象上,但是因为目录本身不包含真是数据,它并没有被真的压缩;不过,被这个属性标记的目录告诉文件系统来压缩新添加到这个目录的文件。任何可以设置在目录上的文件属性也将被设置到新添加到该目录的文件,这被称为继承属性。

The CreateFile function provides a parameter for setting certain file attributes when a file is created. In general, these attributes are the most common for an application to use at file creation time, but not all possible file attributes are available to CreateFile. Some file attributes require the use of other functions, such asSetFileAttributes, DeviceIoControl, or DecryptFile after the file already exists. In the case of FILE_ATTRIBUTE_DIRECTORY, the CreateDirectory function is required at creation time becauseCreateFile cannot create directories. The other file attributes that require special handling areFILE_ATTRIBUTE_REPARSE_POINT and FILE_ATTRIBUTE_SPARSE_FILE, which requireDeviceIoControl. For more information, see SetFileAttributes.

CreateFile函数提供了一个参数用于在文件创建时设置某些文件属性。一般来讲,这些属性是应用程序在创建文件时最常使用的,但并不是所有的文件属性都可以被CreateFile使用。一些文件属性要求在文件创建存在后使用其他函数,例如SetFileAttributes, DeviceIoControl, 或者DecryptFile。在FILE_ATTRIBUTE_DIRECTORY案例中,要求CreateDirectory函数因为CreateFile不能创建目录。其他要求特殊处理的文件属性是FILE_ATTRIBUTE_REPARSE_POINT和FILE_ATTRIBUTE_SPARSE_FILE,它们需要DeviceIoControl函数。更多的信息,请参见SetFileAttributes.

As stated previously, file attribute inheritance occurs when a file is created with file attributes read from the directory attributes where the file will be located. The following table summarizes these inherited attributes and how they relate toCreateFile capabilities.

正如之前声明的,文件属性继承发生在 文件创建时使用文件所在的目录属性。下面的表总结了这些继承属性以及他们是如何与CreateFile的能力产生关联的。

Directory attribute stateCreateFile inheritance override capability for new files

FILE_ATTRIBUTE_COMPRESSED set.

No control. Use DeviceIoControl to clear.

FILE_ATTRIBUTE_COMPRESSED not set.

No control. Use DeviceIoControl to set.

FILE_ATTRIBUTE_ENCRYPTED set.

No control. Use DecryptFile.

FILE_ATTRIBUTE_ENCRYPTED not set.

Can be set using CreateFile.

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED set.

No control. Use SetFileAttributes to clear.

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED not set.

No control. Use SetFileAttributes to set.

 

Related topics

Access Control CreateFile DeviceIoControl File Attribute Constants File Compression and Decompression File Encryption File Management Functions Handles and Objects Handle Inheritance Opening a File for Reading or Writing SetFileAttributes


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The error "too many open files" typically occurs when a system reaches its limit for opening files simultaneously. This issue is commonly seen in web servers when there are too many connections to upstream servers or when there is a high volume of incoming requests. To resolve this issue, you can try the following steps: 1. Increase the file limit: You can increase the maximum number of open files allowed by the system. This can be done by modifying the `ulimit` settings. For example, you can run the command `ulimit -n 4096` to set the maximum number of open files to 4096. 2. Optimize your code: Check if there are any file handles that are not being properly closed after use. Make sure you close connections to upstream servers or release any file resources that are no longer needed. 3. Check resource usage: Monitor the resource usage of your server, including CPU, memory, and disk I/O. High resource utilization can contribute to the "too many open files" error. Optimize your code and consider scaling your infrastructure if necessary. 4. Configure connection pooling: If your application connects to upstream servers frequently, consider implementing connection pooling. This allows you to reuse existing connections instead of creating new ones for each request, reducing the number of open files. 5. Review server configuration: Check your web server configuration (e.g., Nginx, Apache) and ensure it is properly tuned for high traffic and handle a large number of connections. Adjusting parameters like worker processes or threads can help alleviate the file limit issue. If the problem persists after following these steps, you may need to consult with a system administrator or a DevOps professional to further investigate and resolve the issue specific to your system setup.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值