CreateFile

  HANDLE CreateFile(lpszName, fdwAccess, fdwShareMode, lpsa, fdwCreate, fdwAttrsAndFlags, hTemplateFile)    
  LPCTSTR lpszName; /* name of the file */
  DWORD fdwAccess; /* access (read/write) mode */
  DWORD fdwShareMode; /* share mode */
  LPSECURITY_ATTRIBUTES lpsa; /* optional security attributes */
  DWORD fdwCreate; /* how to create */
  DWORD fdwAttrsAndFlags; /* file attributes */
  HANDLE hTemplateFile; /* optional file with attributes to copy */

The CreateFile function creates, opens, or truncates a file, returning a handle that can be used to access the file.

Parameters

lpszName

Points to a null-terminated string that specifies the name of the file to create or open.

fdwAccess

Specifies the desired access to the file. This parameter can be some combination of the following values:

Value Meaning

GENERIC_READ Read access to the file is requested. This allows data to be read from the file and the file pointer to be modified.
GENERIC_WRITE Write access to the file is requested. This allows data to be written to the file and the file pointer to be modified.

fdwShareMode

Specifies how this file can be shared. This parameter must be some combination of the following values:

Value Meaning

0 The file cannot be shared.
FILE_SHARE_READ Other open operations may be performed on the file for read access. This flag must be specified if the CreateFile function is opening the client end of a mailslot.
FILE_SHARE_WRITE Other open operations may be performed on the file for write access.

lpsa

Points to a SECURITY_ATTRIBUTES data structure that specifies the security attributes for the file. The file system must support this parameter for it to have an effect.

The SECURITY_ATTRIBUTES structure has the following format:

typedef struct _SECURITY_ATTRIBUTES { /* sa */

DWORD nLength;

LPVOID lpSecurityDescriptor;

BOOL bInheritHandle;

} SECURITY_ATTRIBUTES;

fdwCreate

Specifies the action to take when the file exists and when it does not exist. See the Comments section for more information. This parameter must be one of the following values:

Value Meaning

CREATE_NEW Create a new file. Fail if the specified file already exists.
CREATE_ALWAYS Create a new file. Overwrite the file if it exists.
OPEN_EXISTING Open the file. Fail if the file does not exist.
OPEN_ALWAYS Open the file if it exists. If the file does not exist, then create the file as if fdwCreate were CREATE_NEW.
TRUNCATE_EXISTING Open the file. Fail if the file does not exist. Once opened, the file is truncated so that its size is zero bytes. The caller must open the file with at least GENERIC_WRITE access.

fdwAttrsAndFlags

Specifies the file attributes and flags for the file. Any combination of the following values is acceptable, except that all other file attributes (FILE_ATTRIBUTE_*) override the normal file attribute, FILE_ATTRIBUTE_NORMAL.

Attribute Meaning

FILE_ATTRIBUTE_ARCHIVE File is marked as archive.
FILE_ATTRIBUTE_NORMAL File can be read from or written to.
FILE_ATTRIBUTE_READONLY File is read only.
FILE_ATTRIBUTE_HIDDEN File is a hidden file.
FILE_ATTRIBUTE_SYSTEM File is a system file.

Flag Meaning

FILE_FLAG_WRITE_THROUGH Indicates that the system should always write through any intermediate cache and go directly to the file. The system may still cache writes, but may not lazily flush the writes.
FILE_FLAG_OVERLAPPED Indicates that the system should initialize the file so that ReadFile, WriteFile, ConnectNamedPipe and TransactNamedPipe operations that take a significant time to process will return ERROR_IO_PENDING. An event will be set to the signaled state when the operation completes.
  When FILE_FLAG_OVERLAPPED is specified, the system will not maintain the file pointer. The file position must be passed as part of the OVERLAPPED structure argument to ReadFile and WriteFile. Specifying FILE_FLAG_OVERLAPPED also enables more than one operation to be simultaneously performed with the handle (a simultaneous read and write, for example).
  If this flag is specified, the ReadFile and WriteFile functions must specify an OVERLAPPED structure.
FILE_FLAG_NO_BUFFERING Indicates that the file is to be opened with no intermediate buffering or caching done by the system. Reads and writes to the file must be done on sector boundaries. Buffer addresses for reads and writes must be aligned on disk sector boundaries in memory. You can determine sector size with the GetDiskFreeSpace function.
FILE_FLAG_RANDOM_ACCESS Indicates that the file will be accessed randomly. Win32 uses this flag to optimize file caching.
FILE_FLAG_SEQUENTIAL_SCAN Indicates that the file will be accessed sequentially from beginning to end; the file pointer will not be modified. Win32 uses this flag to optimize file caching. If an application modifies the file pointer, optimum caching may not occur.
FILE_FLAG_DELETE_ON_CLOSE Indicates that the system should immediately delete the file after all of its handles have been closed.
FILE_FLAG_BACKUP_SEMANTICS Indicates that the system should use the semantics in file creation or lookup that are required for backup operations. The lpszName parameter must be relative to the current directory. Developers must use care when using this option because files created with this flag may not be accessible from other Win32 applications.
  This flag is only valid when running on Win32/NT.

If the CreateFile function is used to open the client side of a named pipe, the fdwAttrsAndFlags parameter may also contain Security Quality of Service information. When the calling application specifies the SECURITY_SQOS_PRESENT flag, the fdwAttrsAndFlags parameter may contain some combination of the following values:

Value Impersonation Level

SECURITY_ANONYMOUS Specifies that the client should be impersonated at Anonymous impersonation level.
SECURITY_IDENTIFICATION Specifies that the client should be impersonated at Identification impersonation level.
SECURITY_IMPERSONATION Specifies that the client should be impersonated at Impersonation impersonation level.
SECURITY_DELEGATION Specifies that the client should be impersonated at Delegation impersonation level.

Value Meaning

SECURITY_CONTEXT_TRACKING Specifies that the Security Tracking Mode should be Dynamic. If this flag is not specified, Security Tracking Mode is Static.
SECURITY_EFFECTIVE_ONLY Specifies whether the entire security context of the client is to be made available to the server or only the effective aspects of the context.

hTemplateFile

Specifies an optional handle with GENERIC_READ access to a template file. The template file is used to supply attributes for the file being created. These attributes include the security descriptor, file attributes, and extended attributes. When the new file is created, the relevant attributes from the template file are used in creating the new file. These attributes override any attributes supplied as explicit parameters (by the lpsa or fdwAttrsAndFlags parameters).

Return Value

If the function is successful, the return value is an open handle to the specified file.

If the function fails, the return value is INVALID_HANDLE_VALUE. Use the GetLastError function to obtain extended error information.

Comments

When creating a new file, CreateFile performs the following actions:

Combines the file attributes and flags specified by fdwAttrsAndFlags with FILE_ATTRIBUTE_ARCHIVE.

Sets the file length to zero.

If the hTemplateFile parameter is specified, CreateFile copies the security descriptor and file attributes associated with the template file to the new file. Otherwise, the security descriptor assigned to the new file comes from the lpsa parameter (or from the containing directory) and the file attributes come from fdwAttrsAndFlags.

When opening an existing file, CreateFile performs the following actions:

Combines the file flags specified by fdwAttrsAndFlags with the existing file attributes. CreateFile ignores the file attributes (FILE_ATTRIBUTES_*) specified by fdwAttrsAndFlags.

Sets the file length according to the value of fdwCreate.

Ignores the hTemplateFile parameter.

If the lpsa parameter isn't NULL, CreateFile ignores the lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure. The other structure members are valid; the bInheritHandle member is the only way to indicate whether the file handle can be inherited.

If lpszName points to the name of a named pipe, CreateFile opens the client end of the named pipe. CreateFile will use any instance of the named pipe that is in the listening state. Once opened by CreateFile, the named pipe instance cannot be opened by another client, but the opening process can duplicate the handle as many times as required. The desired access specified when a pipe is opened must be compatible with the access specified in the CreateNamedPipe dwOpenMode parameter.

If the CreateFile function is used to open the client end of a mailslot, the function always returns a handle successfully, even if the mailslot does not exist. In other words, there is no relationship between opening the client end and opening the server end of the mailslot.

CreateFile can be used to return a handle to a communications resource, such as the serial port “COM1”. For communications resources, the fdwShareMode parameter must be 0 (exclusive access), the fdwCreate 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.

CreateFile can be used to return a handle to console input, “CONIN$”. It can also return a handle to the active screen buffer, “CONOUT$”, if the process has an open handle to it (through inheritance or duplication). For both “CONIN$” and “CONOUT$”, the call will fail if the calling process is not attached to a console (either an inherited console or one allocated by AllocConsole). “CONIN$” always refers to the console's input buffer, and “CONOUT$” always refers to the active screen buffer, even if SetStdHandle has been used to redirect Standard Input and Output handles. GetStdHandle can be used to get handles to Standard Input and Standard Output. For console handles, the parameters to CreateFile should be set as follows:

Parameter Value

lpszName Must be “CONIN$” to obtain a handle to console input or “CONOUT$” to obtain a handle to the active screen buffer.
fdwAccess Should be “GENERIC_READ | GENERIC_WRITE”, but can be either one if you want to limit access.
fdwShareMode If the calling process inherited the console, or if you want a child process to be able to access the console, this parameter must be “FILE_SHARE_READ | FILE_SHARE_WRITE”.
lpsa If the calling process wants the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES data structure must be TRUE.
fdwCreate Must be OPEN_EXISTING.
fdwAttrsAndFlags Ignored.
hTemplateFile Ignored.

The CreateFile function may be used as either a wide-character function (where text arguments must use Unicode) or an ANSI function (where text arguments must use characters from the Windows 3.x character set installed).

Example

This example returns a handle to the current console input buffer:

hReadWriteInput = CreateFile("CONIN$",

GENERIC_READ | GENERIC_WRITE,

FILE_SHARE_READ | FILE_SHARE_WRITE, /* share hndls with cmd */

NULL,

OPEN_EXISTING, /* open already created console */

0, /* normal file open */

NULL

);

See Also

CloseHandle ConnectNamedPipe, CreateNamedPipe, GetOverlappedResult, OpenFile, GetDiskFreeSpace