This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, filestream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, andpipe. The function returns a handle that can be used to access the file or device for various types ofI/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 transactedI/O, use theCreateFileTransacted function.
HANDLE CreateFileA( [in] LPCSTR lpFileName, [in] DWORD dwDesiredAccess, [in] DWORD dwShareMode, [in, optional] LPSECURITY_ATTRIBUTES lpSecurityAttributes, [in] DWORD dwCreationDisposition, [in] DWORD dwFlagsAndAttributes, [in, optional] HANDLE hTemplateFile);
[in] lpFileName
The name of the file or device to be created or opened. You may use either forward slashes (/) or backslashes (\) in this name.
By default, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, prepend "\\?\" to the path. For more information, seeNaming Files, Paths, and Namespaces.
Tip
Starting with Windows 10, Version 1607, you can opt-in to remove the MAX_PATH limitation without prepending "\\?\". See the "Maximum Path Length Limitation" section ofNaming Files, Paths, and Namespaces for details.
For information on special device names, seeDefining 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 moreinformation, seeFile Streams.
[in] dwDesiredAccess
The requested access to the file or device, which can be summarized as read, write, both or 0 to indicate neither).
The most commonly used values areGENERIC_READ,GENERIC_WRITE, or both(GENERIC_READ | GENERIC_WRITE
). For more information, seeGeneric Access Rights,File Security and Access Rights,File Access Rights Constants, andACCESS_MASK.
If this parameter is zero, the application can query certain metadata such as file, directory, or deviceattributes without accessing that file or device, even ifGENERIC_READ access wouldhave been denied.
You cannot request an access mode that conflicts with the sharing mode that is specified by thedwShareMode parameter in an open request that already has an open handle.
For more information, see the Remarks section of this topic andCreating and Opening Files.
[in] dwShareMode
The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, ornone (refer to the following table). Access requests to attributes or extended attributes are not affected bythis flag.
If this parameter is zero andCreateFile succeeds, thefile 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 existingrequest that has an open handle.CreateFile would fail andtheGetLastError function would returnERROR_SHARING_VIOLATION.
To enable a process to share a file or device while another process has the file or device open, use acompatible combination of one or more of the following values. For more information about valid combinations ofthis parameter with thedwDesiredAccess parameter, seeCreating and Opening Files.
[in, optional] lpSecurityAttributes
A pointer to aSECURITY_ATTRIBUTESstructure that contains two separate but related data members: an optional security descriptor, and a Booleanvalue that determines whether the returned handle can be inherited by child processes.
This parameter can beNULL.
If this parameter isNULL, the handle returned byCreateFile cannot be inherited by any child processes theapplication may create and the file or device associated with the returned handle gets a default securitydescriptor.
ThelpSecurityDescriptor member of the structure specifies aSECURITY_DESCRIPTOR for a file or device. Ifthis member isNULL, the file or device associated with the returned handle isassigned a default security descriptor.
CreateFile ignores thelpSecurityDescriptor member when opening an existing file or device, but continuesto use thebInheritHandle member.
ThebInheritHandle member of the structure specifies whether the returned handlecan be inherited.
For more information, see the Remarks section.
[in] dwCreationDisposition
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 toOPEN_EXISTING.
For more information, see the Remarks section.
This parameter must be one of the following values, which cannot be combined:
[in] dwFlagsAndAttributes
The file or device attributes and flags,FILE_ATTRIBUTE_NORMAL being the mostcommon default value for files.
This parameter can include any combination of the available file attributes(FILE_ATTRIBUTE_*). All other file attributes overrideFILE_ATTRIBUTE_NORMAL.
This parameter can also contain combinations of flags (FILE_FLAG_*) for control offile or device caching behavior, access modes, and other special-purpose flags. These combine with anyFILE_ATTRIBUTE_* values.
This parameter can also contain Security Quality of Service (SQOS) information by specifying theSECURITY_SQOS_PRESENT flag. Additional SQOS-related flags information is presented inthe table following the attributes and flags tables.
For more advanced access to file attributes, seeSetFileAttributes. For a complete listof all file attributes with their values and descriptions, seeFile Attribute Constants.
Attribute | Meaning |
---|---|
| The file should be archived. Applications use this attribute to mark files for backup or removal. |
| 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, seeFile Encryption. This flag has no effect ifFILE_ATTRIBUTE_SYSTEM is also specified. This flag is not supported on Home, Home Premium, Starter, or ARM editions of Windows. |
| The file is hidden. Do not include it in an ordinary directory listing. |
| The file does not have other attributes set. This attribute is valid only if used alone. |
| 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. |
| The file is read only. Applications can read the file, but cannot write to or delete it. |
| The file is part of or used exclusively by an operating system. |
| The file is being used for temporary storage. For more information, see theCaching Behavior section of thistopic. |
Flag | Meaning |
---|---|
| 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 hasSE_BACKUP_NAME andSE_RESTORE_NAME privileges. For more information, seeChanging Privileges in a Token. You must set this flag to obtain a handle to a directory. A directory handle can be passed to somefunctions instead of a file handle. For more information, see the Remarks section. |
| 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 theFILE_SHARE_DELETE share mode. Subsequent open requests for the file fail, unless theFILE_SHARE_DELETE sharemode is specified. |
| 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 withCreateFile using theFILE_FLAG_NO_BUFFERING flag, for details seeFile Buffering. |
| 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. |
| Normalreparse 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 theCREATE_ALWAYS flag. If the file is not a reparse point, then this flag is ignored. For more information, see the Remarks section. |
| 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 theOVERLAPPED structure will be set to thesignaled 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 writefunctions specify anOVERLAPPED structure. For information about considerations when using a file handle created with this flag, see theSynchronous and Asynchronous I/O Handlessection of this topic. |
| 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. |
| 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 andFILE_FLAG_NO_BUFFERING. For more information, see theCaching Behavior section of thistopic. |
| The file or device is being opened with session awareness. If this flag is not specified, then per-session devices (such as a device using RemoteFX USB Redirection) cannot be opened by processes running in session 0. This flag has no effect for callers not in session 0. This flag is supported only on server editions of Windows. Windows Server 2008 R2 and Windows Server 2008: This flag is not supported before Windows Server 2012. |
| 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, reverse scans) will be used. This flag has no effect if the file system does not support cached I/O andFILE_FLAG_NO_BUFFERING. For more information, see theCaching Behavior section of thistopic. |
| Write operations will not go through any intermediate cache, they will go directly to disk. For additional information, see theCaching Behavior section of thistopic. |
ThedwFlagsAndAttributes parameter can also specify SQOS information. For moreinformation, seeImpersonation Levels. When thecalling application specifies theSECURITY_SQOS_PRESENT flag as part ofdwFlagsAndAttributes, it can also contain one or more of the following values.
[in, optional] hTemplateFile
A valid handle to a template file with theGENERIC_READ access right. The templatefile supplies file attributes and extended attributes for the file that is being created.
This parameter can beNULL.
When opening an existing file,CreateFile ignores thisparameter.
When opening a new encrypted file, the file inherits the discretionary access control list from its parentdirectory. For additional information, seeFile Encryption.
If the function succeeds, the return value is an open handle to the specified file, device, named pipe, ormail slot.
If the function fails, the return value isINVALID_HANDLE_VALUE. To get extendederror information, callGetLastError.
CreateFile was originally developed specifically for fileinteraction but has since been expanded and enhanced to include most other types of I/O devices and mechanismsavailable to Windows developers. This section attempts to cover the varied issues developers may experience whenusingCreateFile in different contexts and with different I/Otypes. The text attempts to use the wordfile only when referring specifically to data stored in anactual file on a file system. However, some uses offile may be referring more generally to an I/Oobject that supports file-like mechanisms. This liberal use of the termfile is particularlyprevalent in constant names and parameter names because of the previously mentioned historical reasons.
When an application is finished using the object handle returned byCreateFile, use theCloseHandle function to close the handle. This not onlyfrees up system resources, but can have wider influence on things like sharing the file or device and committingdata to disk. Specifics are noted within this topic as appropriate.
Windows Server 2003 and Windows XP: A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remotecomputer when the value of thedwDesiredAccess parameter is theDELETE access flag (0x00010000)OR'ed with any other access flag, and the remote fileor directory has not been opened withFILE_SHARE_DELETE. To avoid the sharing violationin this scenario, open the remote file or directory with theDELETE access right only,or callDeleteFile without first opening the file ordirectory for deletion.
Some file systems, such as the NTFS file system, support compression or encryption for individual files anddirectories. On volumes that have a mounted file system with this support, a new file inherits the compressionand encryption attributes of its directory.
You cannot useCreateFile to control compression,decompression, or decryption on a file or directory. For more information, seeCreating and Opening Files,File Compression and Decompression,andFile Encryption.
Windows Server 2003 and Windows XP: For backward compatibility purposes,CreateFile doesnot apply inheritance rules when you specify a security descriptor inlpSecurityAttributes. To support inheritance, functions that later query the securitydescriptor of this file may heuristically determine and report that inheritance is in effect. For moreinformation, seeAutomatic Propagation of Inheritable ACEs.
As stated previously, if thelpSecurityAttributes parameter isNULL, the handle returned byCreateFile cannot be inherited by any child processes yourapplication may create. The following information regarding this parameter also applies:
Technology | Supported |
---|---|
Server Message Block (SMB) 3.0 protocol | Yes |
SMB 3.0 Transparent Failover (TFO) | See remarks |
SMB 3.0 with Scale-out File Shares (SO) | See remarks |
Cluster Shared Volume File System (CsvFS) | Yes |
Resilient File System (ReFS) | Yes |
Note thatCreateFile with supersede disposition will fail if performed on a file where there is already an open alternate data stream.
Some of these flags should not be combined. For instance, combiningFILE_FLAG_RANDOM_ACCESS withFILE_FLAG_SEQUENTIAL_SCAN isself-defeating.
Specifying theFILE_FLAG_SEQUENTIAL_SCAN flag can increase performance forapplications that read large files using sequential access. Performance gains can be even more noticeable forapplications that read large files mostly sequentially, but occasionally skip forward over small ranges ofbytes. If an application moves the file pointer for random access, optimum caching performance most likely willnot occur. However, correct operation is still guaranteed.
The flagsFILE_FLAG_WRITE_THROUGH andFILE_FLAG_NO_BUFFERING are independent and may be combined.
IfFILE_FLAG_WRITE_THROUGH is used butFILE_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.
IfFILE_FLAG_WRITE_THROUGH andFILE_FLAG_NO_BUFFERING areboth specified, so that system caching is not in effect, then the data is immediately flushed to disk withoutgoing through the Windows system cache. The operating system also requests a write-through of the hard disk'slocal hardware cache to persistent media.
A write-through request viaFILE_FLAG_WRITE_THROUGH also causes NTFS to flush anymetadata changes, such as a time stamp update or a rename operation, that result from processing the request.For this reason, theFILE_FLAG_WRITE_THROUGH flag is often used with theFILE_FLAG_NO_BUFFERING flag as a replacement for calling theFlushFileBuffers function after each write, which cancause unnecessary performance penalties. Using these flags together avoids those penalties. For generalinformation about the caching of files and metadata, seeFile Caching.
WhenFILE_FLAG_NO_BUFFERING is combined withFILE_FLAG_OVERLAPPED, the flags give maximum asynchronous performance, because the I/Odoes 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, whencreating an empty file). To ensure that the metadata is flushed to disk, use theFlushFileBuffers function.
Specifying theFILE_ATTRIBUTE_TEMPORARY attribute causes file systems to avoidwriting data back to mass storage if sufficient cache memory is available, because an application deletes atemporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Althoughit does not directly control data caching in the same way as the previously mentioned flags, theFILE_ATTRIBUTE_TEMPORARY attribute does tell the system to hold as much as possible inthe system cache without writing and therefore may be of concern for certain applications.
If you callCreateFile on a file that is pending deletionas a result of a previous call toDeleteFile, the functionfails. The operating system delays file deletion until all handles to the file are closed.GetLastError returnsERROR_ACCESS_DENIED.
ThedwDesiredAccess parameter can be zero, allowing the application to query fileattributes without accessing the file if the application is running with adequate security settings. This isuseful to test for the existence of a file without opening it for read and/or write access, or to obtain otherstatistics about the file or directory. SeeObtaining and Setting File InformationandGetFileInformationByHandle.
IfCREATE_ALWAYS andFILE_ATTRIBUTE_NORMAL arespecified,CreateFile fails and sets the last error toERROR_ACCESS_DENIED if the file exists and has theFILE_ATTRIBUTE_HIDDEN orFILE_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 useGENERIC_READ | GENERIC_WRITE
fordwDesiredAccess than to useGENERIC_WRITE alone. Theresulting 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 returnERROR_ACCESS_DENIED.
For more information, seeCreating and Opening Files.
To open a directory usingCreateFile, specify theFILE_FLAG_BACKUP_SEMANTICS flag as part ofdwFlagsAndAttributes. Appropriate security checks still apply when this flag is usedwithoutSE_BACKUP_NAME andSE_RESTORE_NAME privileges.
When usingCreateFile to open a directory duringdefragmentation of a FAT or FAT32 file system volume, do not specify theMAXIMUM_ALLOWED access right. Access to the directory is denied if this is done.Specify theGENERIC_READ access right instead.
For more information, seeAbout Directory Management.
Windows Server 2003 and Windows XP: Direct access to the disk or to a volume is not restricted in this manner.
You can use theCreateFile function to open a physicaldisk drive or a volume, which returns a direct access storage device (DASD) handle that can be used with theDeviceIoControl function. This enables you to accessthe disk or volume directly, for example such disk metadata as the partition table. However, this type of accessalso exposes the disk drive or volume to potential data loss, because an incorrect write to a disk using thismechanism could make its contents inaccessible to the operating system. To ensure data integrity, be sure tobecome familiar withDeviceIoControl and how otherAPIs 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:
String | Meaning |
---|---|
"\\.\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 theDeviceIoControl function withIOCTL_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 canspan multiple physical disks.
For an example of opening a physical drive, seeCalling DeviceIoControl.
When opening a volume or removable media drive (for example, a floppy disk drive or flash memory thumb drive),thelpFileName 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.
String | Meaning |
---|---|
"\\.\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, seeNaming a Volume.
A volume contains one or more mounted file systems. Volume handles can be opened as noncached at thediscretion of the particular file system, even when the noncached option is not specified inCreateFile. You should assume that all Microsoft filesystems 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 thenoncached option is specified when opening a volume, buffer alignment is enforced regardless of the file systemon the volume. It is recommended on all file systems that you open volume handles as noncached, and follow thenoncached I/O restrictions.
For more information, seeBackup.
To specify a COM port number greater than 9, use the following syntax:"\\.\COM10". This syntax works for all port numbers and hardware thatallows COM port numbers to be specified.
For more information about communications, seeCommunications.
Parameters | Value |
---|---|
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 theSetStdHandle function redirects the standard inputhandle. To get the standard input handle, use theGetStdHandle function. CONOUT$ gets a handle to the active screen buffer, even ifSetStdHandle redirects the standard output handle. Toget the standard output handle, useGetStdHandle. |
dwDesiredAccess | GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access. |
dwShareMode | When opening CONIN$, specifyFILE_SHARE_READ. When opening CONOUT$, specifyFILE_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 |
lpSecurityAttributes | If you want the console to be inherited, thebInheritHandle member of theSECURITY_ATTRIBUTES structure must beTRUE. |
dwCreationDisposition | You should specifyOPEN_EXISTING when usingCreateFile to open the console. |
dwFlagsAndAttributes | Ignored. |
hTemplateFile | Ignored. |
The following table shows various settings ofdwDesiredAccess andlpFileName.
lpFileName | dwDesiredAccess | Result |
---|---|---|
"CON" | GENERIC_READ | Opens console for input. |
"CON" | GENERIC_WRITE | Opens console for output. |
"CON" | GENERIC_READ | GENERIC_WRITE | CausesCreateFile to fail;GetLastError returnsERROR_FILE_NOT_FOUND. |
For more information, seeMailslots.
If theCreateNamedPipe function was notsuccessfully called on the server prior to this operation, a pipe will not exist andCreateFile will fail withERROR_FILE_NOT_FOUND.
If there is at least one active pipe instance but there are no available listener pipes on the server, whichmeans all pipe instances are currently connected,CreateFile fails withERROR_PIPE_BUSY.
For more information, seePipes.
Example file operations are shown in the following topics:
Working with a mailslot is shown inWriting to a Mailslot.
A tape backup code snippet can found atCreating a Backup Application.
Note
The fileapi.h header defines CreateFile as an alias that automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that is not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, seeConventions for Function Prototypes.
Requirement | Value |
---|---|
Minimum supported client | Windows XP [desktop apps only] |
Minimum supported server | Windows Server 2003 [desktop apps only] |
Target Platform | Windows |
Header | fileapi.h (include Windows.h) |
Library | Kernel32.lib |
DLL | Kernel32.dll |
Creating, Deleting, and Maintaining Files
Device Input and Output Control (IOCTL)
File Compression and Decompression
File Security and Access Rights
Functions
Obtaining and Setting File Information
Overview Topics
Was this page helpful?
Was this page helpful?