Platform SDK: Files and I/O |
The CreateFile function creates or opens the following objects and returns a handle that can be used to access the object:
HANDLE CreateFile( LPCTSTR lpFileName, // file name DWORD dwDesiredAccess, // access mode DWORD dwShareMode, // share mode LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD DWORD dwCreationDisposition, // how to create DWORD dwFlagsAndAttributes, // file attributes HANDLE hTemplateFile // handle to template file );
Windows NT/2000: In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to nearly 32,000 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see File Name Conventions.
Windows 95/98: This string must not exceed MAX_PATH characters.
Value | Meaning |
---|---|
0 | Specifies device query access to the object. An application can query device attributes without accessing the device. |
GENERIC_READ | Specifies read access to the object. Data can be read from the file and the file pointer can be moved. Combine with GENERIC_WRITE for read/write access. |
GENERIC_WRITE | Specifies write access to the object. Data can be written to the file and the file pointer can be moved. Combine with GENERIC_READ for read/write access. |
In addition, you can specify the following access flags.
Value | Documented |
---|---|
DELETE | Standard Access Rights |
READ_CONTROL | Standard Access Rights |
WRITE_DAC | Standard Access Rights |
WRITE_OWNER | Standard Access Rights |
SYNCHRONIZE | Standard Access Rights |
STANDARD_RIGHTS_REQUIRED | Standard Access Rights |
STANDARD_RIGHTS_READ | Standard Access Rights |
STANDARD_RIGHTS_WRITE | Standard Access Rights |
STANDARD_RIGHTS_EXECUTE | Standard Access Rights |
STANDARD_RIGHTS_ALL | Standard Access Rights |
SPECIFIC_RIGHTS_ALL | ACCESS_MASK |
ACCESS_SYSTEM_SECURITY | ACCESS_MASK |
MAXIMUM_ALLOWED | ACCESS_MASK |
GENERIC_READ | ACCESS_MASK |
GENERIC_WRITE | ACCESS_MASK |
GENERIC_EXECUTE | ACCESS_MASK |
GENERIC_ALL | ACCESS_MASK |
To share the object, use a combination of one or more of the following values.
Value | Meaning |
---|---|
FILE_SHARE_DELETE | Windows NT/2000: Subsequent open operations on the object will succeed only if delete access is requested. |
FILE_SHARE_READ | Subsequent open operations on the object will succeed only if read access is requested. |
FILE_SHARE_WRITE | Subsequent open operations on the object will succeed only if write access is requested. |
Windows NT/2000: The lpSecurityDescriptor member of the structure specifies a security descriptor for the object. If lpSecurityAttributes is NULL, the object gets a default security descriptor. The target file system must support security on files and directories for this parameter to have an effect on files.
Value | Meaning |
---|---|
CREATE_NEW | Creates a new file. The function fails if the specified file already exists. |
CREATE_ALWAYS | Creates a new file. If the file exists, the function overwrites the file and clears the existing attributes. |
OPEN_EXISTING | Opens the file. The function fails if the file does not exist.
For a discussion of why you should use the OPEN_EXISTING flag if you are using the CreateFile function for devices, see Remarks. |
OPEN_ALWAYS | Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW. |
TRUNCATE_EXISTING | Opens the file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least GENERIC_WRITE access. The function fails if the file does not exist. |
Any combination of the following attributes is acceptable for the dwFlagsAndAttributes parameter, except all other file attributes override FILE_ATTRIBUTE_NORMAL.
Attribute | Meaning |
---|---|
FILE_ATTRIBUTE_ARCHIVE | The file should be archived. Applications use this attribute to mark files for backup or removal. |
FILE_ATTRIBUTE_ENCRYPTED | 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.
This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also specified. |
FILE_ATTRIBUTE_HIDDEN | The file is hidden. It is not to be included in an ordinary directory listing. |
FILE_ATTRIBUTE_NORMAL | The file has no other attributes set. This attribute is valid only if used alone. |
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | The file will not be indexed by the content indexing service. |
FILE_ATTRIBUTE_OFFLINE | The data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software in Windows 2000. Applications should not arbitrarily change this attribute. |
FILE_ATTRIBUTE_READONLY | The file is read only. Applications can read the file but cannot write to it or delete it. |
FILE_ATTRIBUTE_SYSTEM | The file is part of or is used exclusively by the operating system. |
FILE_ATTRIBUTE_TEMPORARY | The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed. |
Any combination of the following flags is acceptable for the dwFlagsAndAttributes parameter.
Flag | Meaning |
---|---|
FILE_FLAG_WRITE_THROUGH | Instructs the system to write through any intermediate cache and go directly to disk. The system can still cache write operations, but cannot lazily flush them. |
FILE_FLAG_OVERLAPPED | Instructs the system to initialize the object, so that operations that take a significant amount of time to process return ERROR_IO_PENDING. When the operation is finished, the specified event is set to the signaled state.
When you specify FILE_FLAG_OVERLAPPED, the file read and write functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing. When FILE_FLAG_OVERLAPPED is specified, the system does not maintain the file pointer. The file position must be passed as part of the lpOverlapped parameter (pointing to an OVERLAPPED structure) to the file read and write functions. This flag also enables more than one operation to be performed simultaneously with the handle (a simultaneous read and write operation, for example). |
FILE_FLAG_NO_BUFFERING | Instructs the system to open the file with no intermediate buffering or caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager. However, some I/O operations will take longer, because data is not being held in the cache.
An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:
One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume's sector size. An application can determine a volume's sector size by calling the GetDiskFreeSpace function. |
FILE_FLAG_RANDOM_ACCESS | Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching. |
FILE_FLAG_SEQUENTIAL_SCAN | Indicates that the file is to be accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed.
Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes. |
FILE_FLAG_DELETE_ON_CLOSE | Indicates that the operating system is to delete the file immediately after all of its handles have been closed, not just the handle for which you specified FILE_FLAG_DELETE_ON_CLOSE.
Subsequent open requests for the file will fail, unless FILE_SHARE_DELETE is used. |
FILE_FLAG_BACKUP_SEMANTICS | Windows NT/2000: Indicates that the file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks, provided it has the necessary privileges. The relevant privileges are SE_BACKUP_NAME and SE_RESTORE_NAME.
You can also set this flag to obtain a handle to a directory. A directory handle can be passed to some Win32 functions in place of a file handle. |
FILE_FLAG_POSIX_SEMANTICS | Indicates that the file is to be accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support such naming. Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS or 16-bit Windows. |
FILE_FLAG_OPEN_REPARSE_POINT | Specifying this flag inhibits the reparse behavior of NTFS reparse points. When the file is opened, a file handle is returned, whether the filter that controls the reparse point is operational or not. This flag cannot be used with the CREATE_ALWAYS flag. |
FILE_FLAG_OPEN_NO_RECALL | Indicates that the file data is requested, but it should continue to reside in remote storage. It should not be transported back to local storage. This flag is intended for use by remote storage systems or the Hierarchical Storage Management system. |
If the CreateFile function opens the client side of a named pipe, the dwFlagsAndAttributes parameter can also contain Security Quality of Service information. For more information, see Impersonation Levels. When the calling application specifies the SECURITY_SQOS_PRESENT flag, the dwFlagsAndAttributes parameter can contain one or more of the following values.
Value | Meaning |
---|---|
SECURITY_ANONYMOUS | Specifies to impersonate the client at the Anonymous impersonation level. |
SECURITY_IDENTIFICATION | Specifies to impersonate the client at the Identification impersonation level. |
SECURITY_IMPERSONATION | Specifies to impersonate the client at the Impersonation impersonation level. |
SECURITY_DELEGATION | Specifies to impersonate the client at the Delegation impersonation level. |
SECURITY_CONTEXT_TRACKING | Specifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static. |
SECURITY_EFFECTIVE_ONLY | Specifies that 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 flag allows the client to limit the groups and privileges that a server can use while impersonating the client. |
Windows 95: The hTemplateFile parameter must be NULL. If you supply a handle, the call fails and GetLastError returns ERROR_NOT_SUPPORTED.
If the function succeeds, the return value is an open handle to the specified file. If the specified file exists before the function call and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.
If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
Use the CloseHandle function to close an object handle returned by CreateFile.
As noted above, specifying zero for dwDesiredAccess allows an application to query device attributes without actually accessing the device. This type of querying is useful, for example, if an application wants to determine the size of a floppy disk drive and the formats it supports without having a floppy in the drive.
MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.
If you are attempting to create a file on a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a CD, the system displays a message box asking the user to insert a disk or a CD, respectively. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS.
When creating a new file, the CreateFile function performs the following actions:
When opening an existing file, CreateFile performs the following actions:
Windows NT/2000: If you rename or delete a file, then restore it shortly thereafter, Windows NT searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.
Windows NT/2000: Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new file inherits the compression and encryption attributes of its directory.
You cannot use the CreateFile function to set a file's compression state. Use the DeviceIoControl function to set a file's compression state.
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, once opened, the named pipe instance cannot be opened by another client. The access specified when a pipe is opened must be compatible with the access specified in the dwOpenMode parameter of the CreateNamedPipe function. For more information about pipes, see Pipes.
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 about mailslots, see Mailslots.
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, and the hTemplate parameter must be NULL. Read, write, or read/write access can be specified, and the handle can be opened for overlapped I/O. For more information about communications, see Communications.
Volume handles may be opened as noncached at the discretion of the file system, even when the noncached option is not specified with CreateFile. You should assume that all Microsoft file systems open volume handles as noncached. The restrictions on noncached I/O for files apply to volumes as well.
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.
Windows NT/2000: You can use the CreateFile function to open a disk drive or a partition on a disk drive. The function returns a handle to the disk device; that handle can be used with the DeviceIOControl function. The following requirements must be met in order for such a call to succeed:
String | Meaning |
---|---|
\\.\PHYSICALDRIVE2 | Obtains a handle to the third physical drive on the user's computer. |
For an example showing how to open a physical drive, see Calling DeviceIoControl on Windows NT/2000.
String | Meaning |
---|---|
\\.\A: | Obtains a handle to drive A on the user's computer. |
\\.\C: | Obtains a handle to drive C on the user's computer. |
There is no trailing backslash in a drive name. The string "\\.\c:\" refers to the root directory of drive C.
On Windows 2000, you can also open a volume by referring to its unique volume name. In this case also, there should be no trailing backslash on the unique volume name.
Note that all I/O buffers should be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size), even if the disk device is opened without the FILE_FLAG_NO_BUFFERING flag. Depending the disk, this requirement may not be enforced.
Windows 95: This technique does not work for opening a logical drive. In Windows 95, specifying a string in this form causes CreateFile to return an error.
Windows NT/2000: You can open tape drives using a file name of the form \\.\TAPEx
where x is a number indicating which drive to open, starting with tape drive 0. To open tape drive 0 in C, use the file name "\\\\.\\TAPE0". For more information on manipulating tape drives for backup or other applications, see Tape Backup.
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.
Parameters | Value |
---|---|
lpFileName | Use the CONIN$ value to specify console input and the CONOUT$ value to specify console output. |
CONIN$ gets a handle to the console's input buffer, even if the SetStdHandle function redirected 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 redirected 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 | If the calling process inherited 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 list shows the effects of various settings of fwdAccess and lpFileName.
lpFileName | fwdAccess | Result |
---|---|---|
CON | GENERIC_READ | Opens console for input. |
CON | GENERIC_WRITE | Opens console for output. |
CON | GENERIC_READ GENERIC_WRITE |
Windows 95: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND.
Windows NT/2000: Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND. |
An application cannot create a directory with CreateFile; it must call CreateDirectory or CreateDirectoryEx to create a directory.
Windows NT/2000: You can obtain a handle to a directory by setting the FILE_FLAG_BACKUP_SEMANTICS flag. A directory handle can be passed to some Win32 functions in place of a file handle.
Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent directory.
You cannot use the CreateFile function to set a directory's compression state. Use the DeviceIoControl function to set a directory's compression state.
Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.
File I/O Overview, File I/O Functions, ACCESS_MASK, AllocConsole, CloseHandle, ConnectNamedPipe, CreateDirectory, CreateDirectoryEx, CreateNamedPipe, DeviceIOControl, GetDiskFreeSpace, GetOverlappedResult, GetStdHandle, OpenFile, OVERLAPPED, ReadFile, SECURITY_ATTRIBUTES, SetErrorMode, SetStdHandle, Standard Access Rights, TransactNamedPipe, Unique Volume Names, VirtualAlloc, WriteFile