Win API for file operat function

CreateFile

The CreateFile function creates or opens the following objects and returns a handle that can be used to access the object:

  • Consoles
  • Communications resources
  • Directories (open only)
  • Disk devices
  • Files
  • Mailslots
  • Pipes
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
);
Parameters
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the object to create or open.

Windows NT/2000/XP: 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/Me: This string must not exceed MAX_PATH characters.

dwDesiredAccess
[in] Specifies the type of access to the object. An application can obtain read access, write access, read/write access, or device query access. This parameter can be any combination of the following values.
ValueMeaning
0Specifies device query access to the object. An application can query device attributes without accessing the device.
GENERIC_READSpecifies 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_WRITESpecifies 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.

ValueDocumented
DELETEStandard Access Rights
READ_CONTROLStandard Access Rights
WRITE_DACStandard Access Rights
WRITE_OWNERStandard Access Rights
SYNCHRONIZEStandard Access Rights
STANDARD_RIGHTS_REQUIREDStandard Access Rights
STANDARD_RIGHTS_READStandard Access Rights
STANDARD_RIGHTS_WRITEStandard Access Rights
STANDARD_RIGHTS_EXECUTEStandard Access Rights
STANDARD_RIGHTS_ALLStandard Access Rights
SPECIFIC_RIGHTS_ALLACCESS_MASK
ACCESS_SYSTEM_SECURITYACCESS_MASK
MAXIMUM_ALLOWEDACCESS_MASK
GENERIC_READACCESS_MASK
GENERIC_WRITEACCESS_MASK
GENERIC_EXECUTEACCESS_MASK
GENERIC_ALLACCESS_MASK

dwShareMode
[in] Specifies how the object can be shared. If dwShareMode is 0, and CreateFile succeeds, the object cannot be shared and cannot be opened again until the handle is closed. Please refer the information concerning sharing violations in the Remarks section.

To share the object, use a combination of one or more of the following values.

ValueMeaning
FILE_SHARE_DELETEWindows NT/2000/XP: Subsequent open operations on the object will succeed only if delete access is requested.
FILE_SHARE_READSubsequent open operations on the object will succeed only if read access is requested.
FILE_SHARE_WRITESubsequent open operations on the object will succeed only if write access is requested.

lpSecurityAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpSecurityAttributes is NULL, the handle cannot be inherited.

Windows NT/2000/XP: 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.

dwCreationDisposition
[in] Specifies which action to take on files that exist, and which action to take when files do not exist. For more information about this parameter, see the Remarks section. This parameter must be one of the following values.
ValueMeaning
CREATE_NEWCreates a new file. The function fails if the specified file already exists.
CREATE_ALWAYSCreates a new file. If the file exists, the function overwrites the file, clears the existing attributes, and combines the file attributes and flags specified by dwFlagsAndAttributes with FILE_ATTRIBUTE_ARCHIVE.
OPEN_EXISTINGOpens 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_ALWAYSOpens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW.
TRUNCATE_EXISTINGOpens 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.

dwFlagsAndAttributes
[in] Specifies the file attributes and flags for the file.

Any combination of the following attributes is acceptable for the dwFlagsAndAttributes parameter, except all other file attributes override FILE_ATTRIBUTE_NORMAL.

AttributeMeaning
FILE_ATTRIBUTE_ARCHIVEThe file should be archived. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_ENCRYPTEDThe 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_HIDDENThe file is hidden. It is not to be included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMALThe file has no other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_NOT_CONTENT_INDEXEDThe file will not be indexed by the content indexing service.
FILE_ATTRIBUTE_OFFLINEThe 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. Applications should not arbitrarily change this attribute.
FILE_ATTRIBUTE_READONLYThe file is read only. Applications can read the file but cannot write to it or delete it.
FILE_ATTRIBUTE_SYSTEMThe file is part of or is used exclusively by the operating system.
FILE_ATTRIBUTE_TEMPORARYThe 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.

FlagMeaning
FILE_FLAG_WRITE_THROUGHInstructs 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_OVERLAPPEDInstructs 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_BUFFERINGInstructs 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:

  • File access must begin at byte offsets within the file that are integer multiples of the volume's sector size.
  • File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.
  • Buffer addresses for read and write operations should be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size). Depending on the disk, this requirement may not be enforced.

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_ACCESSIndicates that the file is accessed randomly. The system can use this as a hint to optimize file caching.
FILE_FLAG_SEQUENTIAL_SCANIndicates 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_CLOSEIndicates 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_SEMANTICSWindows NT/2000/XP: 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 functions in place of a file handle.

FILE_FLAG_POSIX_SEMANTICSIndicates 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_POINTSpecifying 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_RECALLIndicates 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.

ValueMeaning
SECURITY_ANONYMOUSSpecifies to impersonate the client at the Anonymous impersonation level.
SECURITY_IDENTIFICATIONSpecifies to impersonate the client at the Identification impersonation level.
SECURITY_IMPERSONATIONSpecifies to impersonate the client at the Impersonation impersonation level.
SECURITY_DELEGATIONSpecifies to impersonate the client at the Delegation impersonation level.
SECURITY_CONTEXT_TRACKINGSpecifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static.
SECURITY_EFFECTIVE_ONLYSpecifies 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.


hTemplateFile
[in] Specifies a handle with GENERIC_READ access to a template file. The template file supplies file attributes and extended attributes for the file being created.

Windows 95/98/Me: The hTemplateFile parameter must be NULL. If you supply a handle, the call fails and GetLastError returns ERROR_NOT_SUPPORTED.

Return Values

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.

Remarks

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.

Windows 95/98/Me: CreateFileW is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.

Windows 2000/XP: A sharing violation will occur if an attempt is made to open a file or directory for deletion on a remote machine when the value of the dwDesiredAccess parameter is the DELETE access flag OR'ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE share access. To avoid the sharing violation in this scenario, open the remote file or directory with DELETE access only or call DeleteFile without first opening the file or directory for deletion.

Windows 2000/XP: If CREATE_ALWAYS is specified as the value of the dwCreationDisposition parameter and FILE_ATTRIBUTE_NORMAL is specified as the value of the dwFlagsAndAttributes parameter, CreateFile will fail and set the error GetLastError reports to ACCESS_DENIED. In this case, set the value of the dwFlagsAndAttributes parameter to the ORed value of the FILE_ATTRIBUTE_HIDDEN and FILE_ATTRIBUTE_NORMAL attributes to avoid this error.

Files

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:

  • Clears the existing file attributes.
  • Combines the file attributes and flags specified by dwFlagsAndAttributes with FILE_ATTRIBUTE_ARCHIVE.
  • Sets the file length to zero.
  • Copies the extended attributes supplied by the template file to the new file if the hTemplateFile parameter is specified.

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

  • Combines the file flags specified by dwFlagsAndAttributes with existing file attributes. CreateFile ignores the file attributes specified by dwFlagsAndAttributes.
  • Sets the file length according to the value of dwCreationDisposition.
  • Ignores the hTemplateFile parameter.
  • Ignores the lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure if the lpSecurityAttributes parameter is not NULL. The other structure members are used. The bInheritHandle member is the only way to indicate whether the file handle can be inherited.

Windows NT/2000/XP: If you rename or delete a file, then restore it shortly thereafter, the system searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.

Windows NT/2000/XP: 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.

When multiple processes try to open the same file, or a single process tries to open the file several times, a sharing violation can occur after the first time the file is opened if the second and subsequent open operations specify either a sharing mode that is different from the access mode specified in the first open operation, or the second and subsequent open operations specify an access mode that is different from the sharing mode specified in the first open operation. In other words, Windows cannot provide for conflicting sharing-mode requests in multiple open operations of a single file.

Two examples of this sharing violation scenario would be the following:

  • If you specify the GENERIC_READ and GENERIC_WRITE access modes along with the FILE_SHARE_READ sharing mode in your first call to CreateFile. If you specify the GENERIC_WRITE access mode in your second call to CreateFile, then the function will fail with a sharing violation because the first call opened the file in read-only mode.
  • If you specify the GENERIC_READ and GENERIC_WRITE access modes along with the FILE_SHARE_READ and FILE_SHARE_WRITE sharing modes in your first call to CreateFile. If you specify the GENERIC_READ and GENERIC_WRITE access modes and the FILE_SHARE_READ sharing mode only in your second call to CreateFile, the function will fail with a sharing violation because the read-only sharing mode specified in the second call conflicts with the read/write access that has been granted in the first call.
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, 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.

Mailslots

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.

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

Disk Devices

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/XP: 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:

  • The caller must have administrative privileges for the operation to succeed on a hard disk drive.
  • The lpFileName string should be of the form //./PHYSICALDRIVEx to open the hard disk x. Hard disk numbers start at zero. For example:
StringMeaning
//./PHYSICALDRIVE2Obtains 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.

  • The lpFileName string should be //./x: to open a floppy drive x or a partition x on a hard disk. For example:
StringMeaning
//./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 or later, 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/98/Me: This technique does not work for opening a logical drive. Specifying a string in this form causes CreateFile to return an error.

  • The dwCreationDisposition parameter must have the OPEN_EXISTING value.
  • When opening a floppy disk or a partition on a hard disk, you must set the FILE_SHARE_WRITE flag in the dwShareMode parameter.
Tape Drives

Windows NT/2000/XP: 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.

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
lpFileNameUse 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.
dwDesiredAccessGENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.
dwShareModeIf 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.
lpSecurityAttributesIf you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.
dwCreationDispositionYou should specify OPEN_EXISTING when using CreateFile to open the console.
dwFlagsAndAttributesIgnored.
hTemplateFileIgnored.

The following list shows the effects of various settings of fwdAccess and lpFileName.

lpFileNamefwdAccessResult
CONGENERIC_READOpens console for input.
CONGENERIC_WRITEOpens console for output.
CONGENERIC_READ
GENERIC_WRITE
Windows 95/98/Me: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND.

Windows NT/2000/XP: Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.


Directories

An application cannot create a directory with CreateFile; it must call CreateDirectory or CreateDirectoryEx to create a directory.

Windows NT/2000/XP: You can obtain a handle to a directory by setting the FILE_FLAG_BACKUP_SEMANTICS flag. A directory handle can be passed to some 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.

When using CreateFile to open a directory during defragmentation of a FAT or FAT32 volume, do not specify the MAXIMUM_ALLOWED access mask value. Access to the directory will be denied if this is done. Specify the GENERIC_READ access mask value instead.

Example Code

For an example, see Creating and Opening Files.

Requirements

  Windows NT/2000/XP: Included in Windows NT 3.1 and later.
  Windows 95/98/Me: Included in Windows 95 and later.
  Header: Declared in Winbase.h; include Windows.h.
  Library: Use Kernel32.lib.
  Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000/XP. Also supported by Microsoft Layer for Unicode.

 

WriteFile

The WriteFile function writes data to a file and is designed for both synchronous and asynchronous operation. The function starts writing data to the file at the position indicated by the file pointer. After the write operation has been completed, the file pointer is adjusted by the number of bytes actually written, except when the file is opened with FILE_FLAG_OVERLAPPED. If the file handle was created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the write operation is finished.

This function is designed for both synchronous and asynchronous operation. The WriteFileEx function is designed solely for asynchronous operation. It lets an application perform other processing during a file write operation.

BOOL WriteFile(
  HANDLE hFile,                    // handle to file
  LPCVOID lpBuffer,                // data buffer
  DWORD nNumberOfBytesToWrite,     // number of bytes to write
  LPDWORD lpNumberOfBytesWritten,  // number of bytes written
  LPOVERLAPPED lpOverlapped        // overlapped buffer
);
Parameters
hFile
[in] Handle to the file to be written to. The file handle must have been created with GENERIC_WRITE access to the file.

Windows NT/2000/XP: For asynchronous write operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept function.

Windows 95/98/Me: For asynchronous write operations, hFile can be a communications resource opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by socket or accept. You cannot perform asynchronous write operations on mailslots, named pipes, or disk files.

lpBuffer
[in] Pointer to the buffer containing the data to be written to the file.
nNumberOfBytesToWrite
[in] Specifies the number of bytes to write to the file.

A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system. To truncate or extend a file, use the SetEndOfFile function.

Named pipe write operations across a network are limited to 65,535 bytes.

lpNumberOfBytesWritten
[out] Pointer to the variable that receives the number of bytes written. WriteFile sets this value to zero before doing any work or error checking.

Windows NT/2000/XP: If lpOverlapped is NULL, lpNumberOfBytesWritten cannot be NULL. If lpOverlapped is not NULL, lpNumberOfBytesWritten can be NULL. If this is an overlapped write operation, you can get the number of bytes written by calling GetOverlappedResult. If hFile is associated with an I/O completion port, you can get the number of bytes written by calling GetQueuedCompletionStatus.

If I/O completion ports are used and you are using a callback routine to free the memory allocated to the OVERLAPPED structure pointed to by the lpOverlapped parameter, specify NULL as the value of this parameter to avoid a memory corruption problem during the deallocation. This memory corruption problem will cause an invalid number of bytes to be returned in this parameter.

Windows 95/98/Me: This parameter cannot be NULL.

lpOverlapped
[in] Pointer to an OVERLAPPED structure. This structure is required if hFile was opened with FILE_FLAG_OVERLAPPED.

If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the write operation is complete.

If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile may return before the write operation has been completed. In this case, WriteFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING. This allows the calling process to continue processing while the write operation is being completed. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the write operation.

If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the write operation starts at the current file position and WriteFile does not return until the operation has been completed.

WriteFile resets the event specified by the hEvent member of the OVERLAPPED structure to a nonsignaled state when it begins the I/O operation. Therefore, there is no need for the caller to do so.

Windows NT/2000/XP: If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the write operation starts at the offset specified in the OVERLAPPED structure and WriteFile does not return until the write operation has been completed.

Windows 95/98/Me: For operations on files, disks, pipes, or mailslots, this parameter must be NULL; a pointer to an OVERLAPPED structure causes the call to fail. However, Windows 95/98/Me supports overlapped I/O on serial and parallel ports.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Note that the time stamps may not be updated correctly for a remote file. To ensure consistent results, use unbuffered I/O. An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:

  • File access must begin at byte offsets within the file that are integer multiples of the volume's sector size. To determine a volume's sector size, call the GetDiskFreeSpace function.
  • File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.
  • Buffer addresses for read and write operations must be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size). One way to sector align buffers is to use the VirtualAlloc function to allocate the buffers. This function allocates memory that is aligned on addresses that are integer multiples of the system's page size. Because both page and volume sector sizes are powers of 2, memory aligned by multiples of the system's page size is also aligned by multiples of the volume's sector size.

If part of the file is locked by another process and the write operation overlaps the locked portion, this function fails.

Accessing the output buffer while a write operation is using the buffer may lead to corruption of the data written from that buffer. Applications must not write to, reallocate, or free the output buffer that a write operation is using until the write operation completes.

Characters can be written to the screen buffer using WriteFile with a handle to console output. The exact behavior of the function is determined by the console mode. The data is written to the current cursor position. The cursor position is updated after the write operation.

The system interprets zero bytes to write as specifying a null write operation and WriteFile does not truncate or extend the file. To truncate or extend a file, use the SetEndOfFile function.

When writing to a nonblocking, byte-mode pipe handle with insufficient buffer space, WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

When an application uses the WriteFile function to write to a pipe, the write operation may not finish if the pipe buffer is full. The write operation is completed when a read operation (using the ReadFile function) makes more buffer space available.

If the anonymous read pipe handle has been closed and WriteFile attempts to write using the corresponding anonymous write pipe handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.

The WriteFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

To cancel all pending asynchronous I/O operations, use the CancelIo function. This function only cancels operations issued by the calling thread for the specified file handle. I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.

If you are attempting to write to a floppy drive that does not have a floppy disk, the system displays a message box prompting the user to retry the operation. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_NOOPENFILEERRORBOX.

Example Code

For an example, see Reading, Writing, and Locking Files.

ReadFile

The ReadFile function reads data from a file, starting at the position indicated by the file pointer. After the read operation has been completed, the file pointer is adjusted by the number of bytes actually read, unless the file handle is created with the overlapped attribute. If the file handle is created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the read operation.

This function is designed for both synchronous and asynchronous operation. The ReadFileEx function is designed solely for asynchronous operation. It lets an application perform other processing during a file read operation.

BOOL ReadFile(
  HANDLE hFile,                // handle to file
  LPVOID lpBuffer,             // data buffer
  DWORD nNumberOfBytesToRead,  // number of bytes to read
  LPDWORD lpNumberOfBytesRead, // number of bytes read
  LPOVERLAPPED lpOverlapped    // overlapped buffer
);
Parameters
hFile
[in] Handle to the file to be read. The file handle must have been created with GENERIC_READ access to the file.

Windows NT/2000/XP: For asynchronous read operations, hFile can be any handle opened with the FILE_FLAG_OVERLAPPED flag by the CreateFile function, or a socket handle returned by the socket or accept function.

Windows 95/98/Me: For asynchronous read operations, hFile can be a communications resource opened with the FILE_FLAG_OVERLAPPED flag by CreateFile, or a socket handle returned by socket or accept. You cannot perform asynchronous read operations on mailslots, named pipes, or disk files.

lpBuffer
[out] Pointer to the buffer that receives the data read from the file.
nNumberOfBytesToRead
[in] Specifies the number of bytes to be read from the file.
lpNumberOfBytesRead
[out] Pointer to the variable that receives the number of bytes read. ReadFile sets this value to zero before doing any work or error checking. If this parameter is zero when ReadFile returns TRUE on a named pipe, the other end of the message-mode pipe called the WriteFile function with nNumberOfBytesToWrite set to zero.

Windows NT/2000/XP: If lpOverlapped is NULL, lpNumberOfBytesRead cannot be NULL. If lpOverlapped is not NULL, lpNumberOfBytesRead can be NULL. If this is an overlapped read operation, you can get the number of bytes read by calling GetOverlappedResult. If hFile is associated with an I/O completion port, you can get the number of bytes read by calling GetQueuedCompletionStatus.

If I/O completion ports are used and you are using a callback routine to free the memory allocated to the OVERLAPPED structure pointed to by the lpOverlapped parameter, specify NULL as the value of this parameter to avoid a memory corruption problem during the deallocation. This memory corruption problem will cause an invalid number of bytes to be returned in this parameter.

Windows 95/98/Me: This parameter cannot be NULL.

lpOverlapped
[in] Pointer to an OVERLAPPED structure. This structure is required if hFile was created with FILE_FLAG_OVERLAPPED.

If hFile was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hFile was created with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the read operation is complete.

If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure and ReadFile may return before the read operation has been completed. In this case, ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING. This allows the calling process to continue while the read operation finishes. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the read operation.

If hFile was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the read operation starts at the current file position and ReadFile does not return until the operation has been completed.

Windows NT/2000/XP: If hFile is not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the read operation starts at the offset specified in the OVERLAPPED structure. ReadFile does not return until the read operation has been completed.

Windows 95/98/Me: For operations on files, disks, pipes, or mailslots, this parameter must be NULL; a pointer to an OVERLAPPED structure causes the call to fail. However, Windows 95/98/Me supports overlapped I/O on serial and parallel ports.

Return Values

The ReadFile function returns when one of the following is true: a write operation completes on the write end of the pipe, the number of bytes requested has been read, or an error occurs.

If the function succeeds, the return value is nonzero.

If the return value is nonzero and the number of bytes read is zero, the file pointer was beyond the current end of the file at the time of the read operation. However, if the file was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the return value is FALSE and GetLastError returns ERROR_HANDLE_EOF when the file pointer goes beyond the current end of file.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If part of the file is locked by another process and the read operation overlaps the locked portion, this function fails.

An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:

  • File access must begin at byte offsets within the file that are integer multiples of the volume's sector size. To determine a volume's sector size, call the GetDiskFreeSpace function.
  • File access must be for numbers of bytes that are integer multiples of the volume's sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.
  • Buffer addresses for read and write operations must be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size). One way to sector align buffers is to use the VirtualAlloc function to allocate the buffers. This function allocates memory that is aligned on addresses that are integer multiples of the system's page size. Because both page and volume sector sizes are powers of 2, memory aligned by multiples of the system's page size is also aligned by multiples of the volume's sector size.

Accessing the input buffer while a read operation is using the buffer may lead to corruption of the data read into that buffer. Applications must not read from, write to, reallocate, or free the input buffer that a read operation is using until the read operation completes.

Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of the ReadFile function.

If a named pipe is being read in message mode and the next message is longer than the nNumberOfBytesToRead parameter specifies, ReadFile returns FALSE and GetLastError returns ERROR_MORE_DATA. The remainder of the message may be read by a subsequent call to the ReadFile or PeekNamedPipe function.

When reading from a communications device, the behavior of ReadFile is governed by the current communication time-outs as set and retrieved using the SetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, see COMMTIMEOUTS.

If ReadFile attempts to read from a mailslot whose buffer is too small, the function returns FALSE and GetLastError returns ERROR_INSUFFICIENT_BUFFER.

If the anonymous write pipe handle has been closed and ReadFile attempts to read using the corresponding anonymous read pipe handle, the function returns FALSE and GetLastError returns ERROR_BROKEN_PIPE.

The ReadFile function may fail and return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

The ReadFile code to check for the end-of-file condition (eof) differs for synchronous and asynchronous read operations.

When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero. The following sample code tests for end-of-file for a synchronous read operation:

  
  
//  Attempt a synchronous read operation. 
bResult  =  ReadFile(hFile,  & inBuffer, nBytesToRead,  & nBytesRead, NULL) ; 
//  Check for end of file. 
if  (bResult  &&   nBytesRead  ==   0 , ) 

    
// we're at the end of the file 
}
 
 

An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile, or during subsequent asynchronous operation.

If EOF is detected at ReadFile time for an asynchronous read operation, ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

If EOF is detected during subsequent asynchronous operation, the call to GetOverlappedResult to obtain the results of that operation returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

To cancel all pending asynchronous I/O operations, use the CancelIo function. This function only cancels operations issued by the calling thread for the specified file handle. I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.

If you are attempting to read from a floppy drive that does not have a floppy disk, the system displays a message box prompting the user to retry the operation. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_NOOPENFILEERRORBOX.

The following sample code illustrates testing for end-of-file for an asynchronous read operation:

  
  
//  set up overlapped structure fields 
gOverLapped.Offset      =   0
gOverLapped.OffsetHigh 
=   0
gOverLapped.hEvent     
=  hEvent; 
 
//  attempt an asynchronous read operation 
bResult  =  ReadFile(hFile,  & inBuffer, nBytesToRead,  & nBytesRead, 
    
& gOverlapped) ; 
 
//  if there was a problem, or the async. operation's still pending ... 
if  ( ! bResult) 

    
// deal with the error code 
    switch (dwError = GetLastError()) 
    

        
case ERROR_HANDLE_EOF: 
        

            
// we have reached the end of the file 
            
// during the call to ReadFile 
 
            
// code to handle that 
        }
 
 
        
case ERROR_IO_PENDING: 
        

            
// asynchronous i/o is still in progress 
 
            
// do something else for a while 
            GoDoSomethingElse() ; 
 
            
// check on the results of the asynchronous read 
            bResult = GetOverlappedResult(hFile, &gOverlapped, 
                
&nBytesRead, FALSE) ; 
 
            
// if there was a problem ... 
            if (!bResult) 
            

                
// deal with the error code 
                switch (dwError = GetLastError()) 
                

                    
case ERROR_HANDLE_EOF: 
                    

                        
// we have reached the end of
                        
// the file during asynchronous
                        
// operation
                    }
 
 
                    
// deal with other error cases 
                }
 
            }
 
        }
 // end case 
 
        
// deal with other error cases 
 
    }
 // end switch 
}
  //  end if 
Example Code

For an example, see Reading, Writing, and Locking Files.

PS//Reading, Writing, and Locking Files code

Reading, Writing, and Locking Files

The ReadFile function requires a file handle that is open for reading, or reading and writing. ReadFile copies a specified number of bytes, from the current position up to the end of the file, to a specified buffer. The current position is either the current file pointer setting or the Offset and OffsetHigh members of the specified OVERLAPPED structure. The function retrieves the actual number of bytes read in a variable specified by its fourth parameter.

The WriteFile function requires a file handle that is open for writing, or writing and reading. WriteFile copies a specified number of bytes, from the current position up to the end of the buffer, to a specified file. The function retrieves the actual number of bytes written in a variable specified by its fourth parameter.

The following example illustrates a possible flow for using callback completion asynchronous I/O.

Completion Routine:

 

VOID IoCompletionRoutine(DWORD dwErrorCode, 
        DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped) 

    
// If an I/O error occurs, display the error and exit. 
 
    
if (dwErrorCode) 
    

        printf(
"FATAL I/O Error %ld I/O Context %lx.%lx "
            dwErrorCode, lpOverlapped, lpOverlapped
->hEvent); 
        ExitProcess(dwErrorCode); 
    }
 
    LocalFree(lpOverlapped); 
}
 Main Thread: 

VOID IoWorkerThread(VOID) 

    HANDLE HandleVector[
2]; 
    DWORD CompletionStatus; 
    PIOREQUEST IoRequestPacket; 
    LPOVERLAPPED Overlapped; 
    BOOL IoOperationStatus; 
 
    HandleVector[
0= IoWorkerListLock; 
    HandleVector[
1= IoWorkerListSemaphore; 
 
    
for(;;) 
    

 
        
// Do an alertable wait on the handle vector. Both objects 
        
// being signaled at the same time means that there is an 
        
// I/O request in the queue and the caller has exclusive 
        
// access to the queue. 
 
        CompletionStatus 
= WaitForMultipleObjectsEx(2, HandleVector, 
                TRUE, INFINITE, TRUE); 
 
        
// If the wait failed, error out. 
 
        
if (CompletionStatus == -1
        

            printf(
"FATAL WAIT ERROR %ld ", GetLastError()); 
            ExitProcess(
1); 
        }
 
        
// If an I/O completion occurred, wait for another 
        
// I/O request or I/O completion. 
 
        
if (CompletionStatus != WAIT_IO_COMPLETION) 
        

 
            
// The wait was satisfied. Ownership of the I/O 
            
// request queue is exclusive, and there is something in 
            
// the queue. To insert something in the queue, the 
            
// inserter gets the list lock (mutex), inserts an entry, 
            
// signals the list semaphore, and finally releases the 
            
// list lock. 
 
            IoRequestPacket 
= RemoveHeadList(&IoRequestList); 
 
            ReleaseMutex(IoWorkerListLock); 
 
            
// Allocate an overlapped structure.
 
            Overlapped 
= LocalAlloc(LMEM_ZEROINIT, 
                    
sizeof(OVERLAPPED)); 
 
            
if (!Overlapped) 
            

                printf(
"FATAL allocation error "); 
                ExitProcess(
1); 
            }
 
 
            Overlapped
->Offset = IoRequestPacket->Offset; 
            Overlapped
->OffsetHigh = IoRequestPacket->OffsetHigh; 
            Overlapped
->hEvent = 
                    IoRequestPacket
->dwAdditionalIoContext; 
 
            
if (IoRequestPacket->bRead) 
            

                IoOperationStatus 
= 
                            ReadFileEx(IoRequestPacket
->hFile, 
                    IoRequestPacket
->lpBuffer, 
                    IoRequestPacket
->dwTransferCount, 
                    Overlapped, IoCompletionRoutine); 
            }
 
            
else 
            

                IoOperationStatus 
= 
                    WriteFileEx(IoRequestPacket
->hFile, 
                        IoRequestPacket
->lpBuffer, 
                        IoRequestPacket
->dwTransferCount, 
                        Overlapped, 
                        IoCompletionRoutine); 
            }
 
 
            
// Test to see if the I/O was queued successfully.
 
            
if (!IoOperationStatus) 
            

                printf(
"FATAL I/O Error %ld I/O Context %lx.%lx "
                    GetLastError(), Overlapped, Overlapped
->hEvent); 
                ExitProcess(
1); 
            }
 
 
            
// The I/O queued successfully. Go back into the 
            
// alertable wait for I/O completion or for 
            
// more I/O requests. 
 
        }
 
    }
 
}
 

 

The SetFilePointer function moves the file pointer a specified number of bytes, relative to the beginning or end of the file, or the file pointer's current position. If a positive number of bytes is specified, SetFilePointer moves the file pointer toward the end of the file; a negative value moves the pointer toward the beginning of the file.

The following example appends one file to the end of another file. The application opens two files by using CreateFile: ONE.TXT is opened for reading, and TWO.TXT is opened for writing. Then the application appends the contents of ONE.TXT to the end of TWO.TXT by reading and writing 4K blocks by using ReadFile and WriteFile. Before writing to the second file, the application sets the second file's pointer to the end of the file by using SetFilePointer and locks the area to be written by using LockFile. This prevents another process from accessing the area while the write is in progress. After each write operation, UnlockFile unlocks the locked area.

 

HANDLE hFile; 
 
HANDLE hAppend; 
 
DWORD  dwBytesRead, dwBytesWritten, dwPos; 
 
char    buff[ 4096 ]; 
 
//  Open the existing file. 
 
hFile 
=  CreateFile( " ONE.TXT " ,      //  open ONE.TXT 
    GENERIC_READ,                  //  open for reading 
     0 ,                             //  do not share 
    NULL,                          //  no security 
    OPEN_EXISTING,                 //  existing file only 
    FILE_ATTRIBUTE_NORMAL,         //  normal file 
    NULL);                         //  no attr. template 

if  (hFile  ==  INVALID_HANDLE_VALUE) 

    ErrorHandler(
"Could not open ONE.");  // process error 
}
 
 
//  Open the existing file, or if the file does not exist, 
//  create a new file. 
 
hAppend 
=  CreateFile( " TWO.TXT " ,    //  open TWO.TXT 
    GENERIC_WRITE,                 //  open for writing 
     0 ,                             //  do not share 
    NULL,                          //  no security 
    OPEN_ALWAYS,                   //  open or create 
    FILE_ATTRIBUTE_NORMAL,         //  normal file 
    NULL);                         //  no attr. template 

if  (hAppend  ==  INVALID_HANDLE_VALUE) 

    ErrorHandler(
"Could not open TWO.");    // process error 
}
 
 
//  Append the first file to the end of the second file. 
//  Lock the second file to prevent another process from 
//  accessing it while writing to it. Unlock the 
//  file when writing is finished. 
 
do  

    
if (ReadFile(hFile, buff, 4096&dwBytesRead, NULL)) 
    

        dwPos 
= SetFilePointer(hAppend, 0, NULL, FILE_END); 
        LockFile(hAppend, dwPos, 
0, dwPos + dwBytesRead, 0); 
        WriteFile(hAppend, buff, dwBytesRead, 
            
&dwBytesWritten, NULL); 
        UnlockFile(hAppend, dwPos, 
0, dwPos + dwBytesRead, 0); 
    }
 
}
  while  (dwBytesRead  ==   4096 ); 
 
//  Close both files.
 
CloseHandle(hFile); 
CloseHandle(hAppend); 
# 高校智慧校园解决方案摘要 智慧校园解决方案是针对高校信息化建设的核心工程,旨在通过物联网技术实现数字化校园的智能化升级。该方案通过融合计算机技术、网络通信技术、数据库技术和IC卡识别技术,初步实现了校园一卡通系统,进而通过人脸识别技术实现了更精准的校园安全管理、生活管理、教务管理和资源管理。 方案包括多个管理系统:智慧校园管理平台、一卡通卡务管理系统、一卡通人脸库管理平台、智能人脸识别消费管理系统、疫情防控管理系统、人脸识别无感识别管理系统、会议签到管理系统、人脸识别通道管理系统和图书馆对接管理系统。这些系统共同构成了智慧校园的信息化基础,通过统一数据库和操作平台,实现了数据共享和信息一致性。 智能人脸识别消费管理系统通过人脸识别终端,在无需接触的情况下快速完成消费支付过程,提升了校园服务效率。疫情防控管理系统利用热成像测温技术、视频智能分析等手段,实现了对校园人员体温监测和疫情信息实时上报,提高了校园公共卫生事件的预防和控制能力。 会议签到管理系统和人脸识别通道管理系统均基于人脸识别技术,实现了会议的快速签到和图书馆等场所的高效通行管理。与图书馆对接管理系统实现了一卡通系统与图书馆管理系统的无缝集成,提升了图书借阅的便捷性。 总体而言,该智慧校园解决方案通过集成的信息化管理系统,提升了校园管理的智能化水平,优化了校园生活体验,增强了校园安全,并提高了教学和科研的效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值