Communications

A communications resource is a physical or logical device that provides a single bidirectional, asynchronous data stream. Serial ports, parallel ports, fax machines, and modems are examples of communications resources. For each communications resource, there is a service provider, consisting of a library or driver, that enables applications to access the resource.

  • About Communications
  • Using the Communications Functions
  • Communication Reference
Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


About Communications

The file input and output (I/O) functions (CreateFile, CloseHandle, ReadFile, ReadFileEx, WriteFile, and WriteFileEx) provide the basic interface for opening and closing a communications resource handle and for performing read and write operations. The Microsoft® Win32® API also includes a set of communications functions that provide access to communications resources. This overview describes the use of file I/O and communications functions.

  • Communications Resource Handles
  • Modification of Communications Resource Settings
  • Communications Resource Configuration
  • Modem Configuration
  • Read and Write Operations
  • Communications Events
  • Extended Functions


Communications Resource Handles

A process uses the CreateFile function to open a handle to a communications resource. For example, specifying COM1 opens a handle to a serial port, and LPT1 opens a handle to a parallel port. If the specified resource is currently being used by another process, CreateFile fails. Any thread of the process can use the handle returned by CreateFile to identify the resource in any of the functions that access the resource.

When using CreateFile to open a handle directly to a device, an application must use the special characters " \\ .\" to identify the device. For example, to open a handle to drive A, specify " \\ .\a:" for the lpszName parameter of CreateFile. The calling process can use the handle in the DeviceIoControl function to send control codes to the device.

When the process calls CreateFile to open a communications resource, it specifies the following attributes:

  • What type of read/write access exists for the specified resource.
  • Whether the handle can be inherited by child processes.
  • Whether the handle can be used in overlapped (asynchronous) I/O operations. (For a description of overlapped operations, see Synchronization.)

When the process uses CreateFile to open a communications resource, it must specify certain values for the following parameters:

  • The fdwShareMode parameter must be zero, opening the resource for exclusive access.
  • The fdwCreate parameter must specify the OPEN_EXISTING flag.
  • The hTemplateFile parameter must be NULL.


Modification of Communications Resource Settings

When the CreateFile function opens a handle to a serial communications resource, the system initializes and configures the resource according to the values set up the last time the resource was opened. Preserving the previous settings enables the user to retain the settings specified through a mode command when the device is reopened. The values inherited from the previous open operation include the configuration settings of the device control block (a DCB structure) and the time-out values used in I/O operations. If the device has never been opened, it is configured with the system defaults.

To determine the initial configuration of a serial communications resource, a process calls the GetCommState function, which fills in a serial port DCB structure with the current configuration settings. To modify this configuration, a process specifies a DCB structure in a call to the SetCommState function.

Members of the DCB structure specify the configuration settings such as the baud rate, the number of data bits per byte, and the number of stop bits per byte. Other DCB members specify special characters and enable parity checking and flow control. When a process needs to modify only a few of these configuration settings, it should first call GetCommState to fill in a DCB structure with the current configuration. Then the process can adjust the important values in the DCB structure and reconfigure the device by calling SetCommState and specifying the modified DCB structure. This procedure ensures that the unmodified members of the DCB structure contain appropriate values. For example, a common error is to configure a device with a DCB structure in which the structure's XonChar member is equal to the XoffChar member.

The BuildCommDCB function provides another way to modify a DCB structure. BuildCommDCB uses a string with the same form as the command-line arguments of the mode command to specify the baud rate, parity scheme, number of stop bits, and number of data bits. The remaining members of DCB are not changed by this function, except that the appropriate members are set to disable XON/XOFF and hardware flow control. BuildCommDCB only modifies a DCB structure; it does not reconfigure the device.

A process can reconfigure a communications resource by using the GetCommProperties function to get information from a device driver about the configuration settings that it supports. The process can use this information to avoid specifying a configuration that is not supported.

The SetCommState function reconfigures the communications resource, but it does not affect the internal output and input buffers of the specified driver. The buffers are not flushed, and pending read and write operations are not terminated prematurely.

A process reinitializes a communications resource by using the SetupComm function, which performs the following tasks:

  • Terminates pending read and write operations, even if they have not been completed.
  • Discards unread characters and frees the internal output and input buffers of the driver associated with the specified resource.
  • Reallocates the internal output and input buffers.

A process is not required to call SetupComm. If it does not, the resource's driver initializes the device with the default settings the first time that the communications resource handle is used.


Communications Resource Configuration

The COMMCONFIG structure defines the configuration of a communications resource, serial or otherwise. The format of the structure varies depending on the type of communications resource (the provider subtype). The first few structure members are common to all communications resources; additional members are defined for specific provider subtypes. Specific service providers may extend the COMMCONFIG structure as well.

An application can get and set the configuration of a communications resource by using the GetCommConfig and SetCommConfig functions. When opened, a communications resource is initialized using the default configuration for its provider subtype. To get and set the default configuration for a provider subtype, use the GetDefaultCommConfig and SetDefaultCommConfig functions.

To prompt the user for configuration information, use the CommConfigDialog function. This function displays a dialog box defined by the service provider and fills in a COMMCONFIG structure based on user input.


Modem Configuration

Modem configuration functions enable you to configure a modem before making a connection. An application can set modem options and determine the features of a modem without using commands specific to any modem device. Following are the general features an application may set before making a call:

  • Primary mode of operation (synchronous, asynchronous, and whether error control is enabled).
  • V.42 error control (defined by CCITT recommendation V.42), including specific parameters. CCITT stands for the International Telegraph and Telephone Consultative Committee.
  • V.42bis (defined by CCITT recommendation V.42bis) and MNP5 data compression.
  • Time-out options, including call setup, inactivity, and buffered data delivery.

Before setting a modem's configuration, an application should determine the capabilities of the modem device by using the GetCommProperties function. This function fills in a COMMPROP structure. This structure contains both a general portion, which applies to all communications devices, and a portion that is specific to each provider subtype. For modem devices, the provider-specific portion of the COMMPROP structure is a MODEMDEVCAPS structure.

An application can get and set the current configuration of a modem by using the GetCommConfig and SetCommConfig functions, both of which use a COMMCONFIG structure. This structure contains both a general portion, which applies to all communications devices, and a portion that is specific to each provider subtype. For modem devices, the provider-specific portion of the COMMCONFIG structure is a MODEMSETTINGS structure.

After configuring a modem, an application can use the Telephony Application Programming Interface (TAPI) to actually establish a connection.

The modem configuration functions do not provide for long-term management and maintenance of a modem. Modem service providers should supply modem configuration dialog boxes for this purpose.


Read and Write Operations

The Win32 API supports both synchronous and asynchronous (overlapped) file I/O operations on serial communications resources. Overlapped operations enable the calling thread to perform other tasks while the operation executes in the background. A thread uses the ReadFile or ReadFileEx function to read from a communications resource, and the WriteFile or WriteFileEx function to write to a communications resource. ReadFile and WriteFile can be performed synchronously or asynchronously. ReadFileEx and WriteFileEx can only be performed asynchronously.

The behavior of these read and write functions is affected by whether the function is executed as an overlapped operation, whether the time-out parameters are associated with the handle, and whether flow control parameters are associated with the handle.

A thread can also write to a communications resource by using the TransmitCommChar function, which transmits a specified character ahead of any pending data in the output buffer. This function is useful for transmitting a high priority signal character to the receiving system. Transmission of the high priority character is still subject to flow control and write time-outs, and the operation is performed synchronously.

A thread can use the PurgeComm function to discard all characters in a device's output or input buffer. PurgeComm can also terminate pending read or write operations, even if the operations have not been completed. If a thread uses PurgeComm to flush an output buffer, the deleted characters are not transmitted. To empty the output buffer while ensuring that the contents are transmitted, a thread can call the FlushFileBuffers function (a synchronous operation). Note, however, that FlushFileBuffers is subject to flow control but not to write time-outs, and it will not return until all pending write operations have been transmitted.


Overlapped Operations

Overlapped operations enable a thread to execute a time-consuming I/O operation in the background, leaving the thread free to perform other tasks. To enable overlapped I/O operations on a communications resource, the thread must specify the FILE_FLAG_OVERLAPPED flag in the CreateFile function when the handle is opened. To execute the ReadFile or WriteFile function as an overlapped operation, the calling thread must specify a pointer to an OVERLAPPED structure.The OVERLAPPED structure must contain a handle to a manual-reset (not an auto-reset) event object. The system sets the state of the event object to not-signaled when a call to the I/O function returns before the operation has been completed. The system sets the state of the event object to signaled when the operation has been completed. The thread uses a wait function to check the current state of the event object or to wait for its state to be signaled.

The ReadFileEx and WriteFileEx functions can be performed only as overlapped operations. The calling thread specifies a pointer to the FileIOCompletionRoutine function, which is executed when the overlapped operation is completed. The completion routine is executed only if the calling thread performs an alertable operation.

For more information about event objects, wait functions, alertable waits, and completion routines, see Synchronization.


Time-Outs

A handle to a communications resource has an associated set of time-out parameters that affect the behavior of read and write operations. Time-outs can cause a ReadFile, ReadFileEx, WriteFile, or WriteFileEx operation to conclude when a time-out interval elapses, even though the specified number of characters have not been read or written. It is not treated as an error when a time-out occurs during a read or write operation (that is, the read or write function's return value indicates success). The count of bytes actually read or written is reported by ReadFile or WriteFile (or by the GetOverlappedResult or FileIOCompletionRoutine function, if the I/O was performed as an overlapped operation).

When an application opens a communications resource, the system sets the resource's time-out values to the values in effect when the resource was last used. If the communications resource has never been opened, the system sets the time-out values to some default value. In either case, an application should always determine the current time-out values after opening the resource, and then explicitly set them to meet its requirements. To determine the current time-out values of a communications resource, use the GetCommTimeouts function. To change the time-out values, use the SetCommTimeouts function.

Two types of time-outs are enabled by the time-out parameters. An interval time-out occurs when the time between the receipt of any two characters exceeds a specified number of milliseconds. Timing starts when the first character is received and is restarted when each new character is received. A total time-out occurs when the total amount of time consumed by a read operation exceeds a calculated number of milliseconds. Timing starts immediately when the I/O operation begins. Write operations support only total time-outs. Read operations support both interval and total time-outs, which can be used separately or combined.

The time, in milliseconds, of the total time-out period for a read or write operation is calculated by using the multiplier and constant values from the COMMTIMEOUTS structure specified in the GetCommTimeouts or SetCommTimeouts function. The following formula is used:

Timeout = (MULTIPLIER * number_of_bytes) + CONSTANT

Using both a multiplier and a constant enables the total time-out period to vary, depending on the amount of data being requested. An application can use only the constant by setting the multiplier to zero, or use only the multiplier by setting the constant to zero. If both the constant and multiplier are zero, total time-out is not used.

If all read time-out parameters are zero, read time-outs are not used, and a read operation is not complete until the requested number of bytes have been read or an error occurs. Similarly, if all write time-out parameters are zero, a write operation is not completed until the requested number of bytes have been written or an error occurs.

If the read interval time-out parameter is the MAXDWORD value and both read total time-out parameters are zero, a read operation is completed immediately after reading whatever characters are available in the input buffer, even if it is empty.

Interval timing forces a read operation to return when there is a lull in reception. A process using interval time-outs can set a fairly short interval parameter, so it can respond quickly to small, isolated bursts of one or a few characters, yet it can still collect large buffers of characters with a single call when data is received in a steady stream.

Time-outs for a write operation can be useful when transmission is blocked by some kind of flow control or when the SetCommBreak function has been called to suspend character transmission.

The following table summarizes the behavior of read operations based on the values specified for total and interval time-outs.

Total | Interval | Behavior
0 | 0 | Returns when the buffer is completely filled. Time-outs are not used.
T | 0 | Returns when the buffer is completely filled or when T milliseconds have elapsed since the beginning of the operation.
0 | Y | Returns when the buffer is completely filled or when Y milliseconds have elapsed between the receipt of any two characters. Timing does not begin until the first character is received.
T | Y | Returns when the buffer is completely filled or when either type of time-out occurs.

Note However, that timing is relative to the system controlling the physical device. For a remote device such as a modem, the timing is relative to the server system to which the modem is attached. Any network propagation delay is not factored in. For example, a client application might specify a total time-out that computes to be 500 milliseconds. When 500 milliseconds have elapsed at the server, a time-out error is returned to the client. If there is a 50 milliseconds network propagation delay, the client will not be notified of the time-out until approximately 50 milliseconds after the time-out actually occurred.

The time-out parameters affect the behavior of overlapped read and write operations on a communications device. With overlapped I/O, the ReadFile, WriteFile, ReadFileEx, or WriteFileEx function can return before the operation has been completed. The time-out parameters can determine when the operation has been completed.


Communications Errors

There are other circumstances where a read or write operation can be completed with fewer than the requested number of characters, even though a time-out has not occurred. Following are some examples:

  • Some drivers support the use of special characters, which complete a read operation immediately with only the characters that have been read up to the point when they are received.
  • The PurgeComm function can be called to prematurely terminate pending read or write operations. This function can also delete the contents of the output or input buffers, or both.
  • If a communications error occurs during a read or write operation, all I/O operations on the communications resource are terminated. Break conditions, parity errors, or framing errors are examples of such errors. When an error occurs, the process must call the ClearCommError function to clear the error flag before it can begin additional I/O operations. ClearCommError reports the specific error that occurred and the current status of the device.


Communications Events

A process can monitor a set of events that occur in a communications resource. For example, an application can use event monitoring to determine when the CTS (clear-to-send) and DSR (data-set-ready) signals change state.

A process can monitor events on a given communications resource by using the SetCommMask function to create an event mask. To determine the current event mask for a communications resource, a process can use the GetCommMask function. The following values specify events that can be monitored.

Value | Meaning
EV_BREAK | A break was detected on input.
EV_CTS | The CTS (clear-to-send) signal changed state.
EV_DSR | The DSR (data-set-ready) signal changed state.
EV_ERR | A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING | A ring indicator was detected.
EV_RLSD | The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR | A character was received and placed in the input buffer.
EV_RXFLAG | The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY | The last character in the output buffer was sent.

After a set of events is specified, a process uses the WaitCommEvent function to wait for one of the events to occur. WaitCommEvent can be used synchronously or as an overlapped operation. For additional information about executing a function as an overlapped operation, see Synchronization.

When one of the events specified in the event mask occurs, the process completes the wait operation and sets an event mask variable to indicate the type of event detected. If the SetCommMask is called for a communications resource while a wait is pending for that resource, WaitCommEvent returns an error.

The WaitCommEvent function detects events that have occurred since the last call to SetCommMask or WaitCommEvent. For example, if you specify the EV_RXCHAR event as a wait-satisfying event, a call to WaitCommEvent will be satisfied if there are characters in the driver's input buffer that have arrived since the last call to WaitCommEvent or SetCommMask. Thus, given the following pseudo-code, any characters received between T1 and T2 will satisfy the next call to WaitCommEvent.

while (we_care)
{
    WaitCommEvent(args)

T1: // Read bytes
    // Process bytes

T2:
}

When monitoring an event that occurs when a signal (CTS, DSR, and so on) changes state, WaitCommEvent reports the change, but not the current state. To query the current state of the CTS (clear-to-send), DSR (data-set-ready), RLSD (receive-line-signal-detect), and ring indicator signals, a process can use the GetCommModemStatus function.


Extended Functions

Some communications functions can be called for a device by using the EscapeCommFunction function. This function sends a code to direct the device to execute an extended function. For example, an application can suspend character transmission with the SETBREAK code and resume transmission with the CLRBREAK code. These particular operations can also be started by calling the SetCommBreak and ClearCommBreak functions. EscapeCommFunction can also be used to implement manual modem control. For example, the CLRDTR and SETDTR codes can be used to implement manual DTR (data-terminal-ready) flow control. Note, however, that an error occurs if a process uses EscapeCommFunction to manipulate the DTR line when the device has been configured to enable DTR handshaking, or the RTS (request-to-send) line if RTS handshaking is enabled.

The DeviceIoControl function enables a process to send an extended function code directly to a specified device driver, causing the device to perform a given operation. DeviceIoControl gives a device associated with a communications resource capabilities not supported by the standard serial communications functions. It enables an application to configure a device using parameters unique to that device as well as to call any device-specific functions.


Using the Communications Functions

  • Configuring a communications resource
  • Monitoring communications events


Configuring a Communications Resource

The following example opens a handle to COM1 and fills in a DCB structure with the current configuration. The DCB structure is then modified and used to reconfigure the device.

/* A sample program to illustrate setting up a serial port. */

#include <windows.h>

int
main(int argc, char *argv[])
{
  DCB dcb;
  HANDLE hCom;
  BOOL fSuccess;
  char *pcCommPort = "COM2";

  hCom = CreateFile( pcCommPort,
                     GENERIC_READ | GENERIC_WRITE,
                     0,    // comm devices must be opened w/exclusive-access
                     NULL, // no security attributes
                     OPEN_EXISTING, // comm devices must use OPEN_EXISTING
                     0,    // not overlapped I/O
                     NULL  // hTemplate must be NULL for comm devices
                     );

  if (hCom == INVALID_HANDLE_VALUE) {
      // Handle the error.
      printf ("CreateFile failed with error %d.\n", GetLastError());
      return (1);
    }

  // We will build on the current configuration, and skip setting the size
  // of the input and output buffers with SetupComm.

  fSuccess = GetCommState(hCom, &dcb);

  if (!fSuccess) {
      // Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
    }

  // Fill in the DCB: baud=57,600 bps, 8 data bits, no parity, and 1 stop bit.

  dcb.BaudRate = CBR_57600;     // set the baud rate
  dcb.ByteSize = 8;             // data size, xmit, and rcv
  dcb.Parity = NOPARITY;        // no parity bit
  dcb.StopBits = ONESTOPBIT;    // one stop bit

  fSuccess = SetCommState(hCom, &dcb);

  if (!fSuccess) {
      // Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
    }

  printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
  return (0);
}


Monitoring Communications Events

The following example code opens the serial port for overlapped I/O, creates an event mask to monitor CTS and DSR signals, and then waits for an event to occur. The WaitCommEvent function should be executed as an overlapped operation so the other threads of the process cannot perform I/O operations during the wait.

HANDLE hCom;
OVERLAPPED o;
BOOL fSuccess;
DWORD dwEvtMask;

hCom = CreateFile( "COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,    // exclusive access
    NULL, // no security attributes
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL
    );

if (hCom == INVALID_HANDLE_VALUE)
{
    // Handle the error.
}

// Set the event mask.

fSuccess = SetCommMask(hCom, EV_CTS | EV_DSR);

if (!fSuccess)
{
    // Handle the error.
}

// Create an event object for use in WaitCommEvent.

o.hEvent = CreateEvent(
    NULL,   // no security attributes
    FALSE,  // auto reset event
    FALSE,  // not signaled
    NULL    // no name
    );

assert(o.hEvent);

if (WaitCommEvent(hCom, &dwEvtMask, &o))
{
    if (dwEvtMask & EV_DSR)
    {
         // To do.
    }

    if (dwEvtMask & EV_CTS)
    {
         // To do.
    }
}


Communication Reference

The following elements are used with communications devices.

  • Communication Functions
  • Communication Structures


Communication Functions

The following functions are used with communications devices.

Function | Description
BuildCommDCB | Fills a specified DCB structure with values specified in a device-control string.
BuildCommDCBAndTimeouts | Translates a device-definition string into appropriate device-control block codes and places them into a device control block.
ClearCommBreak | Restores character transmission for a specified communications device and places the transmission line in a nonbreak state.
ClearCommError | Retrieves information about a communications error and reports the current status of a communications device.
CommConfigDialog | Displays a driver-supplied configuration dialog box.
EscapeCommFunction | Directs a specified communications device to perform an extended function.
GetCommConfig | Retrieves the current configuration of a communications device.
GetCommMask | Retrieves the value of the event mask for a specified communications device.
GetCommModemStatus | Retrieves modem control-register values.
GetCommProperties | Retrieves information about the communications properties for a specified communications device.
GetCommState | Retrieves the current control settings for a specified communications device.
GetCommTimeouts | Retrieves the time-out parameters for all read and write operations on a specified communications device.
GetDefaultCommConfig | Retrieves the default configuration for the specified communications device.
PurgeComm | Discards all characters from the output or input buffer of a specified communications resource.
SetCommBreak | Suspends character transmission for a specified communications device and places the transmission line in a break state.
SetCommConfig | Sets the current configuration of a communications device.
SetCommMask | Specifies a set of events to be monitored for a communications device.
SetCommState | Configures a communications device according to the specifications in a device-control block.
SetCommTimeouts | Sets the time-out parameters for all read and write operations on a specified communications device.
SetDefaultCommConfig | Sets the default configuration for a communications device.
SetupComm | Initializes the communications parameters for a specified communications device.
TransmitCommChar | Transmits a specified character ahead of any pending data in the output buffer of the specified communications device.
WaitCommEvent | Waits for an event to occur for a specified communications device.


BuildCommDCB

The BuildCommDCB function fills a specified DCB structure with values specified in a device-control string. The device-control string uses the syntax of the mode command.

BOOL BuildCommDCB(
  LPCTSTR lpDef,  // device-control string
  LPDCB lpDCB     // device-control block
);

Parameters

lpDef
[in] Pointer to a null-terminated string that specifies device-control information. The string must have the same form as the mode command's command-line arguments. For example, the following string specifies a baud rate of 1200, no parity, 8 data bits, and 1 stop bit:
baud=1200 parity=N data=8 stop=1

The device name is ignored if it is included in the string, but it must specify a valid device, as follows:

COM1: baud=1200 parity=N data=8 stop=1

For further information on mode command syntax, refer to the end-user documentation for your operating system.

lpDCB
[out] Pointer to a DCB structure that receives the information.

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

The BuildCommDCB function adjusts only those members of the DCB structure that are specifically affected by the lpDef parameter, with the following exceptions:

  • If the specified baud rate is 110, the function sets the stop bits to 2 to remain compatible with the system's mode command.
  • By default, BuildCommDCB disables XON/XOFF and hardware flow control. To enable flow control, you must explicitly set the appropriate members of the DCB structure.

The BuildCommDCB function only fills in the members of the DCB structure. To apply these settings to a serial port, use the SetCommState function.

There are older and newer forms of the mode command syntax. The BuildCommDCB function supports both forms. However, you cannot mix the two forms together.

The newer form of the mode command syntax lets you explicitly set the values of the flow control members of the DCB structure. If you use an older form of the mode syntax, the BuildCommDCB function sets the flow control members of the DCB structure, as follows:

  • For a string such as 96,n,8,1 or any other older-form mode string that doesn't end with an x or a p:

    fInX, fOutX, fOutXDsrFlow, and fOutXCtsFlow are all set to FALSE

    fDtrControl is set to DTR_CONTROL_ENABLE

    fRtsControl is set to RTS_CONTROL_ENABLE

  • For a string such as 96,n,8,1,x or any other older-form mode string that ends with an x:

    fInX and fOutX are both set to TRUE

    fOutXDsrFlow and fOutXCtsFlow are both set to FALSE

    fDtrControl is set to DTR_CONTROL_ENABLE

    fRtsControl is set to RTS_CONTROL_ENABLE

  • For a string such as 96,n,8,1,p or any other older-form mode string that ends with a p:

    fInX and fOutX are both set to FALSE

    fOutXDsrFlow and fOutXCtsFlow are both set to TRUE

    fDtrControl is set to DTR_CONTROL_HANDSHAKE

    fRtsControl is set to RTS_CONTROL_HANDSHAKE

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

Communications Overview, Communication Functions, DCB, SetCommState


BuildCommDCBAndTimeouts

The BuildCommDCBAndTimeouts function translates a device-definition string into appropriate device-control block codes and places them into a device control block. The function can also set up time-out values, including the possibility of no time-outs, for a device; the function's behavior in this regard varies based on the contents of the device-definition string.

BOOL BuildCommDCBAndTimeouts(
  LPCTSTR lpDef,                  // device-control string
  LPDCB lpDCB,                    // device-control block
  LPCOMMTIMEOUTS  lpCommTimeouts  // device time-out values
);

Parameters

lpDef
[in] Pointer to a null-terminated string that specifies device-control information for the device. The function takes this string, parses it, and then sets appropriate values in the DCB structure pointed to by lpDCB.
lpDCB
[out] Pointer to a DCB structure that receives information from the device-control information string pointed to by lpDef. This DCB structure defines the control settings for a communications device.
lpCommTimeouts
[in] Pointer to a COMMTIMEOUTS structure that the function can use to set device time-out values.

The BuildCommDCBAndTimeouts function modifies its time-out setting behavior based on the presence or absence of a "TO=xxx" substring in the string specified by lpDef:

  • If that string contains the substring "TO=ON", the function sets up total read and write time-out values for the device based on the time-out structure pointed to by lpCommTimeouts.
  • If that string contains the substring "TO=OFF", the function sets up the device with no time-outs.
  • If that string contains neither the "TO=ON" substring nor the "TO=OFF" substring, the function ignores the time-out structure pointed to by lpCommTimeouts. The time-out structure will not be accessed.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

Communications Overview, Communication Functions, BuildCommDCB, COMMTIMEOUTS, DCB, GetCommTimeouts, SetCommTimeouts


ClearCommBreak

The ClearCommBreak function restores character transmission for a specified communications device and places the transmission line in a nonbreak state.

BOOL ClearCommBreak(
  HANDLE hFile   // handle to communications device
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.

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

A communications device is placed in a break state by the SetCommBreak or EscapeCommFunction function. Character transmission is then suspended until the break state is cleared by calling ClearCommBreak.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, ClearCommError, CreateFile, EscapeCommFunction, SetCommBreak


ClearCommError

The ClearCommError function retrieves information about a communications error and reports the current status of a communications device. The function is called when a communications error occurs, and it clears the device's error flag to enable additional input and output (I/O) operations.

BOOL ClearCommError(
  HANDLE hFile,     // handle to communications device
  LPDWORD lpErrors, // error codes
  LPCOMSTAT lpStat  // communications status
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpErrors
[out] Pointer to a variable to be filled with a mask indicating the type of error. This parameter can be one or more of the following values.
Value | Meaning
CE_BREAK | The hardware detected a break condition.
CE_DNS | Windows 95/98/Me: A parallel device is not selected.
CE_FRAME | The hardware detected a framing error.
CE_IOE | An I/O error occurred during communications with the device.
CE_MODE | The requested mode is not supported, or the hFile parameter is invalid. If this value is specified, it is the only valid error.
CE_OOP | Windows 95/98/Me: A parallel device signaled that it is out of paper.
CE_OVERRUN | A character-buffer overrun has occurred. The next character is lost.
CE_PTO | Windows 95/98/Me: A time-out occurred on a parallel device.
CE_RXOVER | An input buffer overflow has occurred. There is either no room in the input buffer, or a character was received after the end-of-file (EOF) character.
CE_RXPARITY | The hardware detected a parity error.
CE_TXFULL | The application tried to transmit a character, but the output buffer was full.

lpStat
[out] Pointer to a COMSTAT structure in which the device's status information is returned. If lpStat is NULL, no status information is returned.

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

If a communications port has been set up with a TRUE value for the fAbortOnError member of the setup DCB structure, the communications software will terminate all read and write operations on the communications port when a communications error occurs. No new read or write operations will be accepted until the application acknowledges the communications error by calling the ClearCommError function.

The ClearCommError function fills the status buffer pointed to by the lpStat parameter with the current status of the communications device specified by the hFile parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, ClearCommBreak, COMSTAT, CreateFile, DCB


CommConfigDialog

The CommConfigDialog function displays a driver-supplied configuration dialog box.

BOOL CommConfigDialog(
  LPCTSTR lpszName,   // device name string
  HWND hWnd,          // handle to window
  LPCOMMCONFIG lpCC   // configuration information
);

Parameters

lpszName
[in] Pointer to a null-terminated string specifying the name of the device for which a dialog box should be displayed.
hWnd
[in] Handle to the window that owns the dialog box. This parameter can be any valid window handle, or it should be NULL if the dialog box is to have no owner.
lpCC
[in/out] Pointer to a COMMCONFIG structure. This structure contains initial settings for the dialog box before the call, and changed values after the call.

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

The CommConfigDialog function requires a dynamic-link library (DLL) provided by the communications hardware vendor.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: 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.

See Also

Communications Overview, Communication Functions, COMMCONFIG


EscapeCommFunction

The EscapeCommFunction function directs a specified communications device to perform an extended function.

BOOL EscapeCommFunction(
  HANDLE hFile,  // handle to communications device
  DWORD dwFunc   // extended function to perform
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
dwFunc
[in] Specifies the code of the extended function to perform. This parameter can be one of the following values.
Value | Meaning
CLRDTR | Clears the DTR (data-terminal-ready) signal.
CLRRTS | Clears the RTS (request-to-send) signal.
SETDTR | Sends the DTR (data-terminal-ready) signal.
SETRTS | Sends the RTS (request-to-send) signal.
SETXOFF | Causes transmission to act as if an XOFF character has been received.
SETXON | Causes transmission to act as if an XON character has been received.
SETBREAK | Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called (or EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical to the SetCommBreak function. Note that this extended function does not flush data that has not been transmitted.
CLRBREAK | Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is identical to the ClearCommBreak function.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, ClearCommBreak, CreateFile, SetCommBreak


GetCommConfig

The GetCommConfig function retrieves the current configuration of a communications device.

BOOL GetCommConfig(
  HANDLE hCommDev,    // handle to communications service
  LPCOMMCONFIG lpCC,  // configuration information
  LPDWORD lpdwSize    // size of buffer
);

Parameters

hCommDev
[in] Handle to the open communications device.
lpCC
[out] Pointer to a buffer that receives a COMMCONFIG structure.
lpdwSize
[in/out] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by lpCC. When the function returns, the variable contains the number of bytes copied if the function succeeds, or the number of bytes required if the buffer was too small.

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, use the GetLastError function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, SetCommConfig, COMMCONFIG


GetCommMask

The GetCommMask function retrieves the value of the event mask for a specified communications device.

BOOL GetCommMask(
  HANDLE hFile,      // handle to communications device
  LPDWORD lpEvtMask  // event mask
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpEvtMask
[out] Pointer to the variable to be filled with a mask of events that are currently enabled. This parameter can be one or more of the following values.
Value | Meaning
EV_BREAK | A break was detected on input.
EV_CTS | The CTS (clear-to-send) signal changed state.
EV_DSR | The DSR (data-set-ready) signal changed state.
EV_ERR | A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_EVENT1 | An event of the first provider-specific type occurred.
EV_EVENT2 | An event of the second provider-specific type occurred.
EV_PERR | A printer error occurred.
EV_RING | A ring indicator was detected.
EV_RLSD | The RLSD (receive-line-signal-detect) signal changed state.
EV_RX80FULL | The receive buffer is 80 percent full.
EV_RXCHAR | A character was received and placed in the input buffer.
EV_RXFLAG | The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY | The last character in the output buffer was sent.

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

The GetCommMask function uses a mask variable to indicate the set of events that can be monitored for a particular communications resource. A handle to the communications resource can be specified in a call to the WaitCommEvent function, which waits for one of the events to occur. To modify the event mask of a communications resource, use the SetCommMask function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, DCB, SetCommMask, WaitCommEvent


GetCommModemStatus

The GetCommModemStatus function retrieves modem control-register values.

BOOL GetCommModemStatus(
  HANDLE hFile,        // handle to communications device
  LPDWORD lpModemStat  // control-register values
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpModemStat
[out] Pointer to a variable that specifies the current state of the modem control-register values. This parameter can be one or more of the following values.
Value | Meaning
MS_CTS_ON | The CTS (clear-to-send) signal is on.
MS_DSR_ON | The DSR (data-set-ready) signal is on.
MS_RING_ON | The ring indicator signal is on.
MS_RLSD_ON | The RLSD (receive-line-signal-detect) signal is on.

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

The GetCommModemStatus function is useful when you are using the WaitCommEvent function to monitor the CTS, RLSD, DSR, or ring indicator signals. To detect when these signals change state, use WaitCommEvent and then use GetCommModemStatus to determine the state after a change occurs.

The function fails if the hardware does not support the control-register values.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, WaitCommEvent


GetCommProperties

The GetCommProperties function retrieves information about the communications properties for a specified communications device.

BOOL GetCommProperties(
  HANDLE hFile,           // handle to comm device
  LPCOMMPROP lpCommProp   // communications properties
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpCommProp
[out] Pointer to a COMMPROP structure in which the communications properties information is returned. This information can be used in subsequent calls to the SetCommState, SetCommTimeouts, or SetupComm function to configure the communications device.

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

The GetCommProperties function returns information from a device driver about the configuration settings that are supported by the driver.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, COMMPROP, CreateFile, SetCommState, SetCommTimeouts, SetupComm


GetCommState

The GetCommState function retrieves the current control settings for a specified communications device.

BOOL GetCommState(
  HANDLE hFile,  // handle to communications device
  LPDCB lpDCB    // device-control block
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpDCB
[out] Pointer to a DCB structure that receives the control settings information.

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

For an example, see Configuring a Communications Resource.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, DCB, SetCommState


GetCommTimeouts

The GetCommTimeouts function retrieves the time-out parameters for all read and write operations on a specified communications device.

BOOL GetCommTimeouts(
  HANDLE hFile,                  // handle to comm device
  LPCOMMTIMEOUTS lpCommTimeouts  // time-out values
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpCommTimeouts
[out] Pointer to a COMMTIMEOUTS structure in which the time-out information is returned.

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

For more information about time-out values for communications devices, see the SetCommTimeouts function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, COMMTIMEOUTS, SetCommTimeouts


GetDefaultCommConfig

The GetDefaultCommConfig function retrieves the default configuration for the specified communications device.

BOOL GetDefaultCommConfig(
  LPCTSTR lpszName,    // device name string
  LPCOMMCONFIG lpCC,   // configuration information
  LPDWORD lpdwSize     // size of buffer
);

Parameters

lpszName
[in] Pointer to a null-terminated string specifying the name of the device.
lpCC
[out] Pointer to a buffer that receives a COMMCONFIG structure.
lpdwSize
[in/out] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by lpCC. Upon return, the variable contains the number of bytes copied if the function succeeds, or the number of bytes required if the buffer was too small.

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, use the GetLastError function.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: 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.

See Also

Communications Overview, Communication Functions, SetDefaultCommConfig, COMMCONFIG


PurgeComm

The PurgeComm function discards all characters from the output or input buffer of a specified communications resource. It can also terminate pending read or write operations on the resource.

BOOL PurgeComm(
  HANDLE hFile,  // handle to communications resource
  DWORD dwFlags  // action to perform
);

Parameters

hFile
[in] Handle to the communications resource. The CreateFile function returns this handle.
dwFlags
[in] Specifies the action to take. This parameter can be one or more of the following values.
Value | Meaning
PURGE_TXABORT | Terminates all outstanding overlapped write operations and returns immediately, even if the write operations have not been completed.
PURGE_RXABORT | Terminates all outstanding overlapped read operations and returns immediately, even if the read operations have not been completed.
PURGE_TXCLEAR | Clears the output buffer (if the device driver has one).
PURGE_RXCLEAR | Clears the input buffer (if the device driver has one).

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

If a thread uses PurgeComm to flush an output buffer, the deleted characters are not transmitted. To empty the output buffer while ensuring that the contents are transmitted, call the FlushFileBuffers function (a synchronous operation). Note, however, that FlushFileBuffers is subject to flow control but not to write time-outs, and it will not return until all pending write operations have been transmitted.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile


SetCommBreak

The SetCommBreak function suspends character transmission for a specified communications device and places the transmission line in a break state until the ClearCommBreak function is called.

BOOL SetCommBreak(
  HANDLE hFile   // handle to communications device
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, ClearCommBreak, CreateFile


SetCommConfig

The SetCommConfig function sets the current configuration of a communications device.

BOOL SetCommConfig(
  HANDLE hCommDev,    // handle to communications device
  LPCOMMCONFIG lpCC,  // configuration services
  DWORD dwSize        // size of structure
);

Parameters

hCommDev
[in] Handle to the open communications device.
lpCC
[in] Pointer to a COMMCONFIG structure.
dwSize
[in] Specifies the size, in bytes, of the structure pointed to by lpCC.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, GetCommConfig, COMMCONFIG


SetCommMask

The SetCommMask function specifies a set of events to be monitored for a communications device.

BOOL SetCommMask(
  HANDLE hFile,    // handle to communications device
  DWORD dwEvtMask  // mask that identifies enabled events
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
dwEvtMask
[in] Specifies the events to be enabled. A value of zero disables all events. This parameter can be one or more of the following values.
Value | Meaning
EV_BREAK | A break was detected on input.
EV_CTS | The CTS (clear-to-send) signal changed state.
EV_DSR | The DSR (data-set-ready) signal changed state.
EV_ERR | A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING | A ring indicator was detected.
EV_RLSD | The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR | A character was received and placed in the input buffer.
EV_RXFLAG | The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY | The last character in the output buffer was sent.

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

The SetCommMask function specifies the set of events that can be monitored for a particular communications resource. A handle to the communications resource can be specified in a call to the WaitCommEvent function, which waits for one of the events to occur. To get the current event mask of a communications resource, use the GetCommMask function.

For an example, see Monitoring Communications Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, DCB, GetCommMask, SetCommState, WaitCommEvent


SetCommState

The SetCommState function configures a communications device according to the specifications in a device-control block (a DCB structure). The function reinitializes all hardware and control settings, but it does not empty output or input queues.

BOOL SetCommState(
  HANDLE hFile,  // handle to communications device
  LPDCB lpDCB    // device-control block
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpDCB
[in] Pointer to a DCB structure that contains the configuration information for the specified communications device.

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

The SetCommState function uses a DCB structure to specify the desired configuration. The GetCommState function returns the current configuration.

To set only a few members of the DCB structure, you should modify a DCB structure that has been filled in by a call to GetCommState. This ensures that the other members of the DCB structure have appropriate values.

The SetCommState function fails if the XonChar member of the DCB structure is equal to the XoffChar member.

When SetCommState is used to configure the 8250, the following restrictions apply to the values for the DCB structure's ByteSize and StopBits members:

The number of data bits must be 5 to 8 bits.

For an example, see Configuring a Communications Resource.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, BuildCommDCB, CreateFile, DCB, GetCommState


SetCommTimeouts

The SetCommTimeouts function sets the time-out parameters for all read and write operations on a specified communications device.

BOOL SetCommTimeouts(
  HANDLE hFile,                  // handle to comm device
  LPCOMMTIMEOUTS lpCommTimeouts  // time-out values
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpCommTimeouts
[in] Pointer to a COMMTIMEOUTS structure that contains the new time-out values.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, COMMTIMEOUTS, GetCommTimeouts, ReadFile, ReadFileEx, WriteFile, WriteFileEx


SetDefaultCommConfig

The SetDefaultCommConfig function sets the default configuration for a communications device.

BOOL SetDefaultCommConfig(
  LPCTSTR lpszName,    // device name string
  LPCOMMCONFIG lpCC,   // configuration information
  DWORD dwSize         // size of structure
);

Parameters

lpszName
[in] Pointer to a null-terminated string specifying the name of the device.
lpCC
[in] Pointer to a COMMCONFIG structure.
dwSize
[in] Specifies the size, in bytes, of the structure pointed to by lpCC.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: 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.

See Also

Communications Overview, Communication Functions, GetDefaultCommConfig, COMMCONFIG


SetupComm

The SetupComm function initializes the communications parameters for a specified communications device.

BOOL SetupComm(
  HANDLE hFile,     // handle to communications device
  DWORD dwInQueue,  // size of input buffer
  DWORD dwOutQueue  // size of output buffer
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
dwInQueue
[in] Specifies the recommended size, in bytes, of the device's internal input buffer.
dwOutQueue
[in] Specifies the recommended size, in bytes, of the device's internal output buffer.

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

After a process uses the CreateFile function to open a handle to a communications device, it can call SetupComm to set the communications parameters for the device. If it does not set them, the device uses the default parameters when the first call to another communications function occurs.

The dwInQueue and dwOutQueue parameters specify the recommended sizes for the internal buffers used by the driver for the specified device. For example, YMODEM protocol packets are slightly larger than 1024 bytes. Therefore, a recommended buffer size might be 1200 bytes for YMODEM communications. For Ethernet-based communications, a recommended buffer size might be 1600 bytes, which is slightly larger than a single Ethernet frame.

The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances). For example, the function can succeed even though the driver does not allocate a buffer, as long as some other portion of the system provides equivalent functionality.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, SetCommState


TransmitCommChar

The TransmitCommChar function transmits a specified character ahead of any pending data in the output buffer of the specified communications device.

BOOL TransmitCommChar(
  HANDLE hFile,  // handle to communications device
  char cChar     // character to transmit
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
cChar
[in] Specifies the character to be transmitted.

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

The TransmitCommChar function is useful for sending an interrupt character (such as a CTRL+C) to a host system.

If the device is not transmitting, TransmitCommChar cannot be called repeatedly. Once TransmitCommChar places a character in the output buffer, the character must be transmitted before the function can be called again. If the previous character has not yet been sent, TransmitCommChar returns an error.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, WaitCommEvent


WaitCommEvent

The WaitCommEvent function waits for an event to occur for a specified communications device. The set of events that are monitored by this function is contained in the event mask associated with the device handle.

BOOL WaitCommEvent(
  HANDLE hFile,                // handle to comm device
  LPDWORD lpEvtMask,           // event type
  LPOVERLAPPED lpOverlapped,   // overlapped structure
);

Parameters

hFile
[in] Handle to the communications device. The CreateFile function returns this handle.
lpEvtMask
[out] Pointer to a variable that receives a mask indicating the type of event that occurred. If an error occurs, the value is zero; otherwise, it is one of the following values.
Value | Meaning
EV_BREAK | A break was detected on input.
EV_CTS | The CTS (clear-to-send) signal changed state.
EV_DSR | The DSR (data-set-ready) signal changed state.
EV_ERR | A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
EV_RING | A ring indicator was detected.
EV_RLSD | The RLSD (receive-line-signal-detect) signal changed state.
EV_RXCHAR | A character was received and placed in the input buffer.
EV_RXFLAG | The event character was received and placed in the input buffer. The event character is specified in the device's DCB structure, which is applied to a serial port by using the SetCommState function.
EV_TXEMPTY | The last character in the output buffer was sent.

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 operation is complete.

If hFile was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, WaitCommEvent is performed as an overlapped operation. In this case, the OVERLAPPED structure must contain a handle to a manual-reset event object (created by using the CreateEvent function).

If hFile was not opened with FILE_FLAG_OVERLAPPED, WaitCommEvent does not return until one of the specified events or an error occurs.

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

The WaitCommEvent function monitors a set of events for a specified communications resource. To set and query the current event mask of a communications resource, use the SetCommMask and GetCommMask functions.

If the overlapped operation cannot be completed immediately, the function returns FALSE and the GetLastError function returns ERROR_IO_PENDING, indicating that the operation is executing in the background. When this happens, the system sets the hEvent member of the OVERLAPPED structure to the not-signaled state before WaitCommEvent returns, and then it sets it to the signaled state when one of the specified events or an error occurs. The calling process can use one of the wait functions to determine the event object's state and then use the GetOverlappedResult function to determine the results of the WaitCommEvent operation. GetOverlappedResult reports the success or failure of the operation, and the variable pointed to by the lpEvtMask parameter is set to indicate the event that occurred.

If a process attempts to change the device handle's event mask by using the SetCommMask function while an overlapped WaitCommEvent operation is in progress, WaitCommEvent returns immediately. The variable pointed to by the lpEvtMask parameter is set to zero.

For an example, see Monitoring Communications Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Communications Overview, Communication Functions, CreateFile, DCB, GetCommMask, GetOverlappedResult, OVERLAPPED, SetCommMask, SetCommState


Communication Structures

The following structures are used with communications devices.

COMMCONFIG
COMMPROP
COMMTIMEOUTS
COMSTAT
DCB
MODEMDEVCAPS
MODEMSETTINGS


COMMCONFIG

The COMMCONFIG structure contains information about the configuration state of a communications device.

typedef struct _COMM_CONFIG {
  DWORD dwSize;
  WORD  wVersion;
  WORD  wReserved;
  DCB   dcb;
  DWORD dwProviderSubType;
  DWORD dwProviderOffset;
  DWORD dwProviderSize;
  WCHAR wcProviderData[1];
} COMMCONFIG, *LPCOMMCONFIG;

Members

dwSize
Specifies the size, in bytes, of the COMMCONFIG structure.
wVersion
Specifies the version number of the COMMCONFIG structure. This parameter can be 1. The version of the provider-specific structure should be included in the wcProviderData member.
wReserved
Reserved; do not use.
dcb
Specifies a device-control block (DCB) structure for RS-232 serial devices. A DCB structure is always present regardless of the port driver subtype specified in the device's COMMPROP structure.
dwProviderSubType
Identifies the type of communications provider, and thus the format of the provider-specific data. For a list of communications provider types, see the description of the COMMPROP structure.
dwProviderOffset
Specifies the offset, in bytes, of the provider-specific data relative to the beginning of the structure. This member is zero if there is no provider-specific data.
dwProviderSize
Specifies the size, in bytes, of the provider-specific data.
wcProviderData
Contains the provider-specific data, if any. This member can be of any size or can be omitted. Because the COMMCONFIG structure may be expanded in the future, applications should use the dwProviderOffset member to determine the location of this member.

Remarks

If the provider subtype is PST_RS232 or PST_PARALLELPORT, the wcProviderData member is omitted. If the provider subtype is PST_MODEM, the wcProviderData member contains a MODEMSETTINGS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Communications Overview, Communication Structures, DCB, COMMPROP, GetCommProperties, MODEMSETTINGS


COMMPROP

The COMMPROP structure is used by the GetCommProperties function to return information about a given communications driver.

typedef struct _COMMPROP {
  WORD  wPacketLength;
  WORD  wPacketVersion;
  DWORD dwServiceMask;
  DWORD dwReserved1;
  DWORD dwMaxTxQueue;
  DWORD dwMaxRxQueue;
  DWORD dwMaxBaud;
  DWORD dwProvSubType;
  DWORD dwProvCapabilities;
  DWORD dwSettableParams;
  DWORD dwSettableBaud;
  WORD  wSettableData;
  WORD  wSettableStopParity;
  DWORD dwCurrentTxQueue;
  DWORD dwCurrentRxQueue;
  DWORD dwProvSpec1;
  DWORD dwProvSpec2;
  WCHAR wcProvChar[1];
} COMMPROP;

Members

wPacketLength
Specifies the size, in bytes, of the entire data packet, regardless of the amount of data requested.
wPacketVersion
Specifies the version of the structure.
dwServiceMask
Specifies a bitmask indicating which services are implemented by this provider. The SP_SERIALCOMM value is always specified for communications providers, including modem providers.
dwReserved1
Reserved; do not use.
dwMaxTxQueue
Specifies the maximum size, in bytes, of the driver's internal output buffer. A value of zero indicates that no maximum value is imposed by the serial provider.
dwMaxRxQueue
Specifies the maximum size, in bytes, of the driver's internal input buffer. A value of zero indicates that no maximum value is imposed by the serial provider.
dwMaxBaud
Specifies the maximum allowable baud rate, in bits per second (bps). This member can be one of the following values.
Value | Meaning
BAUD_075 | 75 bps
BAUD_110 | 110 bps
BAUD_134_5 | 134.5 bps
BAUD_150 | 150 bps
BAUD_300 | 300 bps
BAUD_600 | 600 bps
BAUD_1200 | 1200 bps
BAUD_1800 | 1800 bps
BAUD_2400 | 2400 bps
BAUD_4800 | 4800 bps
BAUD_7200 | 7200 bps
BAUD_9600 | 9600 bps
BAUD_14400 | 14400 bps
BAUD_19200 | 19200 bps
BAUD_38400 | 38400 bps
BAUD_56K | 56K bps
BAUD_57600 | 57600 bps
BAUD_115200 | 115200 bps
BAUD_128K | 128K bps
BAUD_USER | Programmable baud rates available

dwProvSubType
Specifies the specific communications provider type.
Value | Meaning
PST_FAX | FAX device
PST_LAT | LAT protocol
PST_MODEM | Modem device
PST_NETWORK_BRIDGE | Unspecified network bridge
PST_PARALLELPORT | Parallel port
PST_RS232 | RS-232 serial port
PST_RS422 | RS-422 port
PST_RS423 | RS-423 port
PST_RS449 | RS-449 port
PST_SCANNER | Scanner device
PST_TCPIP_TELNET | TCP/IP Telnet® protocol
PST_UNSPECIFIED | Unspecified
PST_X25 | X.25 standards

dwProvCapabilities
Specifies a bitmask indicating the capabilities offered by the provider. This member can be one of the following values.
Value | Meaning
PCF_16BITMODE | Special 16-bit mode supported
PCF_DTRDSR | DTR (data-terminal-ready)/DSR (data-set-ready) supported
PCF_INTTIMEOUTS | Interval time-outs supported
PCF_PARITY_CHECK | Parity checking supported
PCF_RLSD | RLSD (receive-line-signal-detect) supported
PCF_RTSCTS | RTS (request-to-send)/CTS (clear-to-send) supported
PCF_SETXCHAR | Settable XON/XOFF supported
PCF_SPECIALCHARS | Special character support provided
PCF_TOTALTIMEOUTS | Total (elapsed) time-outs supported
PCF_XONXOFF | XON/XOFF flow control supported

dwSettableParams
Specifies a bitmask indicating the communications parameter that can be changed. This member can be one of the following values.
Value | Meaning
SP_BAUD | Baud rate
SP_DATABITS | Data bits
SP_HANDSHAKING | Handshaking (flow control)
SP_PARITY | Parity
SP_PARITY_CHECK | Parity checking
SP_RLSD | RLSD (receive-line-signal-detect)
SP_STOPBITS | Stop bits

dwSettableBaud
Specifies a bitmask indicating the baud rates that can be used. For values, see the dwMaxBaud member.
wSettableData
Specifies a bitmask indicating the number of data bits that can be set. This member can be one of the following values.
Value | Meaning
DATABITS_5 | 5 data bits
DATABITS_6 | 6 data bits
DATABITS_7 | 7 data bits
DATABITS_8 | 8 data bits
DATABITS_16 | 16 data bits
DATABITS_16X | Special wide path through serial hardware lines

wSettableStopParity
Specifies a bitmask indicating the stop bit and parity settings that can be selected. This member can be one of the following values.
Value | Meaning
STOPBITS_10 | 1 stop bit
STOPBITS_15 | 1.5 stop bits
STOPBITS_20 | 2 stop bits
PARITY_NONE | No parity
PARITY_ODD | Odd parity
PARITY_EVEN | Even parity
PARITY_MARK | Mark parity
PARITY_SPACE | Space parity

dwCurrentTxQueue
Specifies the size, in bytes, of the driver's internal output buffer. A value of zero indicates that the value is unavailable.
dwCurrentRxQueue
Specifies the size, in bytes, of the driver's internal input buffer. A value of zero indicates that the value is unavailable.
dwProvSpec1
Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.

Set this member to COMMPROP_INITIALIZED before calling the GetCommProperties function to indicate that the wPacketLength member is already valid.

dwProvSpec2
Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.
wcProvChar
Specifies provider-specific data. Applications should ignore this member unless they have detailed information about the format of the data required by the provider.

Remarks

The contents of the dwProvSpec1, dwProvSpec2, and wcProvChar members depend on the provider subtype (specified by the dwProvSubType member).

If the provider subtype is PST_MODEM, these members are used as follows.

Value | Meaning
dwProvSpec1 | Not used.
dwProvSpec2 | Not used.
wcProvChar | Contains a MODEMDEVCAPS structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Communications Overview, Communication Structures, GetCommProperties


COMMTIMEOUTS

The COMMTIMEOUTS structure is used in the SetCommTimeouts and GetCommTimeouts functions to set and query the time-out parameters for a communications device. The parameters determine the behavior of ReadFile, WriteFile, ReadFileEx, and WriteFileEx operations on the device.

typedef struct _COMMTIMEOUTS {
  DWORD ReadIntervalTimeout;
  DWORD ReadTotalTimeoutMultiplier;
  DWORD ReadTotalTimeoutConstant;
  DWORD WriteTotalTimeoutMultiplier;
  DWORD WriteTotalTimeoutConstant;
} COMMTIMEOUTS,*LPCOMMTIMEOUTS;

Members

ReadIntervalTimeout
Specifies the maximum time, in milliseconds, allowed to elapse between the arrival of two characters on the communications line. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.

A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received.

ReadTotalTimeoutMultiplier
Specifies the multiplier, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is multiplied by the requested number of bytes to be read.
ReadTotalTimeoutConstant
Specifies the constant, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.

A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations.

WriteTotalTimeoutMultiplier
Specifies the multiplier, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is multiplied by the number of bytes to be written.
WriteTotalTimeoutConstant
Specifies the constant, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written.

A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations.

Remarks

If an application sets ReadIntervalTimeout and ReadTotalTimeoutMultiplier to MAXDWORD and sets ReadTotalTimeoutConstant to a value greater than zero and less than MAXDWORD, one of the following occurs when the ReadFile function is called:

  • If there are any characters in the input buffer, ReadFile returns immediately with the characters in the buffer.
  • If there are no characters in the input buffer, ReadFile waits until a character arrives and then returns immediately.
  • If no character arrives within the time specified by ReadTotalTimeoutConstant, ReadFile times out.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Communications Overview, Communication Structures, GetCommTimeouts, ReadFile, ReadFileEx, SetCommTimeouts, WriteFile, WriteFileEx


COMSTAT

The COMSTAT structure contains information about a communications device. This structure is filled by the ClearCommError function.

typedef struct _COMSTAT {
  DWORD fCtsHold : 1;
  DWORD fDsrHold : 1;
  DWORD fRlsdHold : 1;
  DWORD fXoffHold : 1;
  DWORD fXoffSent : 1;
  DWORD fEof : 1;
  DWORD fTxim : 1;
  DWORD fReserved : 25;
  DWORD cbInQue;
  DWORD cbOutQue;
} COMSTAT, *LPCOMSTAT;

Members

fCtsHold
Specifies whether transmission is waiting for the CTS (clear-to-send) signal to be sent. If this member is TRUE, transmission is waiting.
fDsrHold
Specifies whether transmission is waiting for the DSR (data-set-ready) signal to be sent. If this member is TRUE, transmission is waiting.
fRlsdHold
Specifies whether transmission is waiting for the RLSD (receive-line-signal-detect) signal to be sent. If this member is TRUE, transmission is waiting.
fXoffHold
Specifies whether transmission is waiting because the XOFF character was received. If this member is TRUE, transmission is waiting.
fXoffSent
Specifies whether transmission is waiting because the XOFF character was transmitted. If this member is TRUE, transmission is waiting. Transmission halts when the XOFF character is transmitted to a system that takes the next character as XON, regardless of the actual character.
fEof
Specifies whether the end-of-file (EOF) character has been received. If this member is TRUE, the EOF character has been received.
fTxim
If this member is TRUE, there is a character queued for transmission that has come to the communications device by way of the TransmitCommChar function. The communications device transmits such a character ahead of other characters in the device's output buffer.
fReserved
Reserved; do not use.
cbInQue
Specifies the number of bytes received by the serial provider but not yet read by a ReadFile operation.
cbOutQue
Specifies the number of bytes of user data remaining to be transmitted for all write operations. This value will be zero for a nonoverlapped write.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Communications Overview, Communication Structures, ClearCommError, ReadFile, TransmitCommChar


DCB

The DCB structure defines the control setting for a serial communications device.

typedef struct _DCB {
  DWORD DCBlength;           // sizeof(DCB)
  DWORD BaudRate;            // current baud rate
  DWORD fBinary: 1;          // binary mode, no EOF check
  DWORD fParity: 1;          // enable parity checking
  DWORD fOutxCtsFlow:1;      // CTS output flow control
  DWORD fOutxDsrFlow:1;      // DSR output flow control
  DWORD fDtrControl:2;       // DTR flow control type
  DWORD fDsrSensitivity:1;   // DSR sensitivity
  DWORD fTXContinueOnXoff:1; // XOFF continues Tx
  DWORD fOutX: 1;          // XON/XOFF out flow control
  DWORD fInX: 1;           // XON/XOFF in flow control
  DWORD fErrorChar: 1;     // enable error replacement
  DWORD fNull: 1;          // enable null stripping
  DWORD fRtsControl:2;     // RTS flow control
  DWORD fAbortOnError:1;   // abort on error
  DWORD fDummy2:17;        // reserved
  WORD wReserved;          // not currently used
  WORD XonLim;             // transmit XON threshold
  WORD XoffLim;            // transmit XOFF threshold
  BYTE ByteSize;           // number of bits/byte, 4-8
  BYTE Parity;             // 0-4=no,odd,even,mark,space
  BYTE StopBits;           // 0,1,2 = 1, 1.5, 2
  char XonChar;            // Tx and Rx XON character
  char XoffChar;           // Tx and Rx XOFF character
  char ErrorChar;          // error replacement character
  char EofChar;            // end of input character
  char EvtChar;            // received event character
  WORD wReserved1;         // reserved; do not use
} DCB;

Members

DCBlength
Specifies the length, in bytes, of the DCB structure.
BaudRate
Specifies the baud rate at which the communications device operates. This member can be an actual baud rate value, or one of the following baud rate indexes:

CBR_110
CBR_19200
CBR_300
CBR_38400
CBR_600
CBR_56000
CBR_1200
CBR_57600
CBR_2400
CBR_115200
CBR_4800
CBR_128000
CBR_9600
CBR_256000
CBR_14400

fBinary
Specifies whether binary mode is enabled. The Win32 API does not support nonbinary mode transfers, so this member must be TRUE. Using FALSE will not work.
fParity
Specifies whether parity checking is enabled. If this member is TRUE, parity checking is performed and errors are reported.
fOutxCtsFlow
Specifies whether the CTS (clear-to-send) signal is monitored for output flow control. If this member is TRUE and CTS is turned off, output is suspended until CTS is sent again.
fOutxDsrFlow
Specifies whether the DSR (data-set-ready) signal is monitored for output flow control. If this member is TRUE and DSR is turned off, output is suspended until DSR is sent again.
fDtrControl
Specifies the DTR (data-terminal-ready) flow control. This member can be one of the following values.
Value | Meaning
DTR_CONTROL_DISABLE | Disables the DTR line when the device is opened and leaves it disabled.
DTR_CONTROL_ENABLE | Enables the DTR line when the device is opened and leaves it on.
DTR_CONTROL_HANDSHAKE | Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.

fDsrSensitivity
Specifies whether the communications driver is sensitive to the state of the DSR signal. If this member is TRUE, the driver ignores any bytes received, unless the DSR modem input line is high.
fTXContinueOnXoff
Specifies whether transmission stops when the input buffer is full and the driver has transmitted the XoffChar character. If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the XonChar character to resume reception.
fOutX
Specifies whether XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when the XoffChar character is received and starts again when the XonChar character is received.
fInX
Specifies whether XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is sent when the input buffer comes within XonLim bytes of being empty.
fErrorChar
Specifies whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is TRUE and the fParity member is TRUE, replacement occurs.
fNull
Specifies whether null bytes are discarded. If this member is TRUE, null bytes are discarded when received.
fRtsControl
Specifies the RTS (request-to-send) flow control. This member can be one of the following values.
Value | Meaning
RTS_CONTROL_DISABLE | Disables the RTS line when the device is opened and leaves it disabled.
RTS_CONTROL_ENABLE | Enables the RTS line when the device is opened and leaves it on.
RTS_CONTROL_HANDSHAKE | Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than one-half full and lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.
RTS_CONTROL_TOGGLE | Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent, the RTS line will be low.

fAbortOnError
Specifies whether read and write operations are terminated if an error occurs. If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearCommError function.
fDummy2
Reserved; do not use.
wReserved
Not used; must be set to zero.
XonLim
Specifies the minimum number of bytes allowed in the input buffer before flow control is activated to inhibit the sender. Note that the sender may transmit characters after the flow control signal has been activated, so this value should never be zero. This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in fInX, fRtsControl, or fDtrControl.
XoffLim
Specifies the maximum number of bytes allowed in the input buffer before flow control is activated to allow transmission by the sender. This assumes that either XON/XOFF, RTS, or DTR input flow control is specified in fInX, fRtsControl, or fDtrControl. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer.
ByteSize
Specifies the number of bits in the bytes transmitted and received.
Parity
Specifies the parity scheme to be used. This member can be one of the following values.
Value | Meaning
EVENPARITY | Even
MARKPARITY | Mark
NOPARITY | No parity
ODDPARITY | Odd
SPACEPARITY | Space

StopBits
Specifies the number of stop bits to be used. This member can be one of the following values.
Value | Meaning
ONESTOPBIT | 1 stop bit
ONE5STOPBITS | 1.5 stop bits
TWOSTOPBITS | 2 stop bits

XonChar
Specifies the value of the XON character for both transmission and reception.
XoffChar
Specifies the value of the XOFF character for both transmission and reception.
ErrorChar
Specifies the value of the character used to replace bytes received with a parity error.
EofChar
Specifies the value of the character used to signal the end of data.
EvtChar
Specifies the value of the character used to signal an event.
wReserved1
Reserved; do not use.

Remarks

When a DCB structure is used to configure the 8250, the following restrictions apply to the values specified for the ByteSize and StopBits members:

  • The number of data bits must be 5 to 8 bits.
  • The use of 5 data bits with 2 stop bits is an invalid combination, as is 6, 7, or 8 data bits with 1.5 stop bits.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Communications Overview, Communication Structures, BuildCommDCB, ClearCommError, EscapeCommFunction, GetCommState, SetCommState


MODEMDEVCAPS

The MODEMDEVCAPS structure contains information about the capabilities of a modem.

typedef struct modemdevcaps_tag {
  DWORD dwActualSize;
  DWORD dwRequiredSize;
  DWORD dwDevSpecificOffset;
  DWORD dwDevSpecificSize;
  DWORD dwModemProviderVersion;
  DWORD dwModemManufacturerOffset;
  DWORD dwModemManufacturerSize;
  DWORD dwModemModelOffset;
  DWORD dwModemModelSize;
  DWORD dwModemVersionOffset;
  DWORD dwModemVersionSize;
  DWORD dwDialOptions;
  DWORD dwCallSetupFailTimer;
  DWORD dwInactivityTimeout;
  DWORD dwSpeakerVolume;
  DWORD dwSpeakerMode;
  DWORD dwModemOptions;
  DWORD dwMaxDTERate;
  DWORD dwMaxDCERate;
  BYTE abVariablePortion [1];
} MODEMDEVCAPS, *PMODEMDEVCAPS, *LPMODEMDEVCAPS;

Members

dwActualSize
Specifies the size, in bytes, of the data actually returned to the application. This member may be less than the dwRequiredSize member, if an application did not allocate enough space for the variable-length portion of the structure.
dwRequiredSize
Specifies the number of bytes required for the entire MODEMDEVCAPS structure, including the variable-length portion.
dwDevSpecificOffset
Specifies the offset of the provider-defined portion of the structure, in bytes relative to the beginning of the structure.
dwDevSpecificSize
Specifies the size of the provider-defined portion of the structure, in bytes.
dwModemProviderVersion
Specifies the version of the service provider. The format and use of this member depends on the service provider.
dwModemManufacturerOffset
Specifies the offset of a text string that contains the name of the modem manufacturer. The offset is specified in bytes relative to the beginning of the structure.
dwModemManufacturerSize
Specifies the length of the modem manufacturer name, in bytes. The string is not null-terminated.
dwModemModelOffset
Specifies the offset of a text string that contains the model of the modem. The offset is specified in bytes relative to the beginning of the structure.
dwModemModelSize
Specifies the length of the model name, in bytes. The string is not null-terminated.
dwModemVersionOffset
Specifies the offset of a text string that gives the version and revision of the attached modem, if the provider could determine the information. The offset is specified in bytes relative to the beginning of the structure.
dwModemVersionSize
Specifies the length of the modem version string, in bytes. The string is not null-terminated.
dwDialOptions
Specifies dialing options that are supported by the modem device. This member can be zero or more of the following values.
Value | Meaning
DIALOPTION_BILLING | Specifies that the modem supports waiting for billing tone (bong).
DIALOPTION_QUIET | Specifies that the modem supports waiting for quiet.
DIALOPTION_DIALTONE | Specifies that the modem supports waiting for a dial tone.

dwCallSetupFailTimer
Specifies the maximum call setup timeout supported by the modem, in seconds. This is the largest value that can be specified for the corresponding member of the MODEMSETTINGS structure.
dwInactivityTimeout
Specifies the maximum inactivity timeout supported by the modem, in tenths of seconds. This is the largest value that can be specified for the corresponding member of the MODEMSETTINGS structure.
dwSpeakerVolume
Specifies the speaker volume settings supported by the modem. This member can be zero or more of the following values.
Value | Meaning
MDMVOLFLAG_LOW | The modem supports low (MDMVOL_LOW) volume.
MDMVOLFLAG_MEDIUM | The modem supports medium (MDMVOL_MEDIUM) volume.
MDMVOLFLAG_HIGH | The modem supports high (MDMVOL_HIGH) volume.

dwSpeakerMode
Specifies the speaker mode settings supported by the modem. This member can be zero or more of the following values.
Value | Meaning
MDMSPKRFLAG_OFF | The modem supports the MDMSPKR_OFF speaker mode.
MDMSPKRFLAG_DIAL | The modem supports the MDMSPKR_DIAL speaker mode.
MDMSPKRFLAG_ON | The modem supports the MDMSPKR_ON speaker mode.
MDMSPKRFLAG_CALLSETUP | The modem supports the MDMSPKR_CALLSETUP speaker mode.

dwModemOptions
Specifies supported modem options. This member can be zero or more of the following values:

MDM_BLIND_DIAL
MDM_FLOWCONTROL_SOFT
MDM_CCITT_OVERRIDE
MDM_FORCED_EC
MDM_CELLULAR
MDM_SPEED_ADJUST
MDM_COMPRESSION
MDM_TONE_DIAL
MDM_ERROR_CONTROL
MDM_V23_OVERRIDE
MDM_FLOWCONTROL_HARD

When MODEMDEVCAPS is used to set modem options, as part of the MODEMSETTINGS structure, these values are used as follows.
Value Meaning
MDM_CCITT_OVERRIDE When set, CCITT modulations are enabled for V.21 and V.22 or V.23.

When clear, bell modulations are enabled for 103 and 212A.
MDM_V23_OVERRIDE When set, CCITT modulations are enabled for V.23.

When clear, CCITT modulations are enabled for V.21 and V.22.

For V.23 to be set, both MDM_CCITT_OVERRIDE and MDM_V23_OVERRIDE must be set.

dwMaxDTERate
Maximum DTE rate in bits per second.
dwMaxDCERate
Maximum DCE rate in bits per second.
abVariablePortion
Contains variable-length information, including strings and any provider-defined information.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Mcx.h; include Windows.h.

See Also

Communications Overview, Communication Structures, MODEMSETTINGS


MODEMSETTINGS

The MODEMSETTINGS structure contains information about a modem's configuration.

typedef struct modemsettings_tag {
  DWORD dwActualSize;            // size of returned data
  DWORD dwRequiredSize;          // structure size
  DWORD dwDevSpecificOffset;     // offset of data
  DWORD dwDevSpecificSize;       // size of defined data

  // Static local options (read/write)
  DWORD dwCallSetupFailTimer;      // call setup timeout
  DWORD dwInactivityTimeout;       // timeout
  DWORD dwSpeakerVolume;           // speaker volume level
  DWORD dwSpeakerMode;             // speaker mode
  DWORD dwPreferredModemOptions;   // preferred options

  // Negotiated options (read) for current or last call
  DWORD dwNegotiatedModemOptions;  // options
  DWORD dwNegotiatedDCERate;       // DCE rate

  // Variable portion for proprietary expansion
  BYTE  abVariablePortion[1];      // variable-length data
} MODEMSETTINGS, *PMODEMSETTINGS, *LPMODEMSETTINGS;

Members

dwActualSize
Specifies the size, in bytes, of the data actually returned to the application. This member may be less than the dwRequiredSize member if an application did not allocate enough space for the variable-length portion of the structure.
dwRequiredSize
Specifies the number of bytes required for the entire MODEMDEVCAPS structure, including the variable-length portion.
dwDevSpecificOffset
Specifies the offset of the provider-defined portion of the structure, in bytes relative to the beginning of the structure.
dwDevSpecificSize
Specifies the size of the provider-defined portion of the structure, in bytes.
dwCallSetupFailTimer
Specifies the maximum number of seconds the modem should wait, after dialing is completed, for an indication that a modem-to-modem connection has been established. If a connection is not established in this interval, the call is assumed to have failed. This member is equivalent to register S7 in Hayes® compatible modems.
dwInactivityTimeout
Specifies the maximum number of seconds of inactivity allowed after a connection is established. If no data is either transmitted or received for this period of time, the call is automatically terminated. This time-out is used to avoid excessive long-distance charges or online service charges if an application unexpectedly locks up or the user leaves.
dwSpeakerVolume
Specifies the volume level of the monitor speaker when the speaker is on. This member can be one of the following values.
Value | Meaning
MDMVOL_LOW | Low volume.
MDMVOL_MEDIUM | Medium volume.
MDMVOL_HIGH | High volume.

The MODEMDEVCAPS structure specifies the speaker volumes a modem supports. Actual volumes are hardware-specific.

dwSpeakerMode
Specifies when the speaker should be on. This member can be one of the following values.
Value | Meaning
MDMSPKR_OFF | The speaker is always off.
MDMSPKR_CALLSETUP | The speaker is on until a connection is established.
MDMSPKR_ON | The speaker is always on.
MDMSPKR_DIAL | The speaker is on until a connection is established, except that it is off while the modem is actually dialing.

dwPreferredModemOptions
Specifies the modem options requested by the application. The local and remote modems negotiate modem options during call setup; this member specifies the initial negotiating position of the local modem.

The dwModemOptions member of the MODEMDEVCAPS structure specifies the modem options supported by the local modem. For a list of modem options, see the description of the MODEMDEVCAPS structure.

dwNegotiatedModemOptions
Specifies the modem options that are actually in effect. This member is filled in after a connection is established and the local and remote modems negotiate modem options.

The dwModemOptions member of the MODEMDEVCAPS structure specifies the modem options supported by the local modem. For a list of modem options, see the description of the MODEMDEVCAPS structure.

dwNegotiatedDCERate
Specifies the DCE rate that is in effect. This member is filled in after a connection is established and the local and remote modems negotiate modem modulations.
abVariablePortion
Contains provider-defined information, if any.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Mcx.h; include Windows.h.

See Also

Communications Overview, Communication Structures, MODEMDEVCAPS


Consoles and Character-Mode Support

Consoles manage input and output (I/O) for character-mode applications (applications that do not provide their own graphical user interface).

This overview describes support for character-mode applications.

  • About Character-Mode Support
  • Using the Console
  • Console Reference


About Character-Mode Support

Consoles provide high-level support for simple character-mode applications that interact with the user by using functions that read from standard input and write to standard output or standard error. Consoles also provide sophisticated low-level support that gives direct access to a console's screen buffer and that enables applications to receive extended input information (such as mouse input).

  • Consoles
  • Input and Output Methods
  • Console Code Pages
  • Console Control Handlers


Consoles

A console is an interface that provides I/O to character-mode applications. This processor-independent mechanism makes it easy to port existing character-mode applications or to create new character-mode tools and applications.

A console consists of an input buffer and one or more screen buffers. The input buffer contains a queue of input records, each of which contains information about an input event. The input queue always includes key-press and key-release events. It can also include mouse events (pointer movements and button presses and releases) and events during which user actions affect the size of the active screen buffer. A screen buffer is a two-dimensional array of character and color data for output in a console window.

The console functions enable different levels of access to a console. The high-level console I/O functions enable an application to read from standard input to retrieve keyboard input stored in a console's input buffer. The functions also enable an application to write to standard output or standard error to display text in the console's screen buffer. The high-level functions also support redirection of standard handles and control of console modes for different I/O functionality. The low-level console I/O functions enable applications to receive detailed input about keyboard and mouse events, as well as events involving user interactions with the console window. The low-level functions also enable greater control of output to the screen.


Creation of a Console

The system creates a new console when it starts a console process, a character-mode process whose entry point is the main function. For example, the system creates a new console when it starts the command processor. When the command processor starts a new console process, the user can specify whether the system creates a new console for the new process or whether it inherits the command processor's console. A process can create a console by using one of the following methods:

  • A graphical user interface (GUI) or console process that is not currently attached to a console can use the AllocConsole function to create a new console.
  • A GUI or console process can use the CreateProcess function to create a new console process and specify a flag to tell the system to create a new console.

Typically, a process uses AllocConsole to create a console when an error occurs requiring interaction with the user. For example, a GUI process can create a console when an error occurs that prevents it from using its normal graphical interface, or a console process that does not normally interact with the user can create a console when an error makes it necessary. The process that calls AllocConsole must not be attached to an existing console. GUI processes are not attached to any console when they are created. A console process is not attached to a console if the DETACHED_PROCESS flag was specified in a call to CreateProcess when the process was created. A process can use the FreeConsole function to detach itself from an inherited console or from a console created by AllocConsole.

A process can also create a console by specifying the CREATE_NEW_CONSOLE flag in a call to CreateProcess. This method creates a new console that is accessible to the child process but not to the parent process. Separate consoles enable both parent and child processes to interact with the user without conflict. If this flag is not specified when a console process is created, both processes are attached to the same console, and there is no guarantee that the correct process will receive the input intended for it. Applications can prevent confusion by creating child processes that do not inherit handles of the input buffer, or by enabling only one child process at a time to inherit an input buffer handle while preventing the parent process from reading console input until the child has finished.

Creating a new console results in a new console window, as well as separate I/O screen buffers. The process associated with the new console uses the GetStdHandle function to get the handles of the new console's input and screen buffers. These handles enable the process to access the console.

When a process uses CreateProcess, it can specify a STARTUPINFO structure, whose members control the characteristics of the first new console (if any) created for the child process. The STARTUPINFO structure specified in the call to CreateProcess affects a console created if the CREATE_NEW_CONSOLE flag is specified. It also affects a console created if the child process subsequently uses AllocConsole. The following console characteristics can be specified:

  • The size, in character cells, and the location, in screen pixel coordinates, of the new console window
  • The size, in character cells, of the new console's screen buffer
  • The text and background color attributes of the new console's screen buffer
  • The name appearing in the title bar of the new console's window

The system uses default values if the STARTUPINFO values are not specified. A child process can use the GetStartupInfo function to determine the values in its STARTUPINFO structure.

A process cannot change the location of its console window on the screen, but the following console functions are available to set or retrieve the other properties specified in the STARTUPINFO structure.

Function | Description
GetConsoleScreenBufferInfo | Retrieves the window size, screen buffer size, and color attributes.
SetConsoleWindowInfo | Changes the size of the console window.
SetConsoleScreenBufferSize | Changes the size of the screen buffer.
SetConsoleTextAttribute | Sets the color attributes.
SetConsoleTitle | Sets the console window title.
GetConsoleTitle | Retrieves the console window title.


Closing a Console

A process can use the FreeConsole function to detach itself from its console. If other processes share the console, the console is not destroyed, but the process that called FreeConsole cannot refer to it. After calling FreeConsole, the process can use AllocConsole to create a new console.

A console is closed when the last process attached to it terminates or calls FreeConsole.


Console Handles

A console process uses handles to access the input and screen buffers of its console. A process can use the GetStdHandle, CreateFile, or CreateConsoleScreenBuffer function to open one of these handles.

The GetStdHandle function provides a mechanism for retrieving the standard input (STDIN), standard output (STDOUT), and standard error (STDERR) handles associated with a process. During console creation, the system creates these handles. Initially, STDIN is a handle to the console's input buffer, and STDOUT and STDERR are handles of the console's active screen buffer. However, the SetStdHandle function can redirect the standard handles by changing the handle associated with STDIN, STDOUT, or STDERR. Because the parent's standard handles are inherited by any child process, subsequent calls to GetStdHandle return the redirected handle. A handle returned by GetStdHandle may, therefore, refer to something other than console I/O. For example, before creating a child process, a parent process can use SetStdHandle to set a pipe handle to be the STDIN handle that is inherited by the child process. When the child process calls GetStdHandle, it gets the pipe handle. This means that the parent process can control the standard handles of the child process. The handles returned by GetStdHandle have GENERIC_READ | GENERIC_WRITE access unless SetStdHandle has been used to set the standard handle to have lesser access.

The value of the handles returned by GetStdHandle will not be 0, 1, and 2, so the standard predefined stream constants in the STDIO.H header file (STDIN, STDOUT, and STDERR) cannot be used in functions that require a console handle.

The CreateFile function enables a process to get a handle to its console's input buffer and active screen buffer, even if STDIN and STDOUT have been redirected. To open a handle to a console's input buffer, specify the CONIN$ value in a call to CreateFile. Specify the CONOUT$ value in a call to CreateFile to open a handle to a console's active screen buffer. CreateFile enables you to specify the read/write access of the handle that it returns.

The CreateConsoleScreenBuffer function creates a new screen buffer and returns a handle. This handle can be used in any function that accepts a handle to console output. The new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. Note that changing the active screen buffer does not affect the handle returned by GetStdHandle. Similarly, using SetStdHandle to change the STDOUT handle does not affect the active screen buffer.

Console handles returned by CreateFile and CreateConsoleScreenBuffer can be used in any of the console functions that require a handle to a console's input buffer or of a console screen buffer. Handles returned by GetStdHandle can be used by the console functions if they have not been redirected to refer to something other than console I/O. If a standard handle has been redirected to refer to a file or a pipe, however, the handle can only be used by the ReadFile and WriteFile functions.

A process can use the DuplicateHandle function to create a duplicate console handle that has different access or inheritability from the original handle. Note, however, that a process can create a duplicate console handle only for its own use. This differs from other handle types (such as file, pipe, or mutex objects), for which DuplicateHandle can create a duplicate that is valid for a different process.

To close a console handle, a process can use the CloseHandle function.


Console Input Buffer

Each console has an input buffer that contains a queue of input event records. When a console's window has the keyboard focus, a console formats each input event (such as a single keystroke, a movement of the mouse, or a mouse-button click) as an input record that it places in the console's input buffer.

Applications can access a console's input buffer indirectly by using the high-level console I/O functions, or directly by using the low-level console I/O functions. The high-level input functions filter and process the data in the input buffer, returning only a stream of input characters. The low-level input functions enable applications to read input records directly from a console's input buffer, or to place input records into the input buffer.

An input record is a structure containing information about the type of event that occurred (keyboard, mouse, window resizing, focus, or menu event) as well as specific details about the event. The EventType member in an INPUT_RECORD structure indicates which type of event is contained in the record.

Focus and menu events are placed in a console's input buffer for internal use by the system and should be ignored by applications.

Keyboard Events

Keyboard events are generated when any key is pressed or released; this includes control keys. However, the ALT key has special meaning to the system when pressed and released without being combined with another character, and it is not passed through to the application. Also, the CTRL+C key combination is not passed through if the input handle is in processed mode.

If the input event is a keystroke, the Event member in INPUT_RECORD is a KEY_EVENT_RECORD structure containing the following information:

  • A Boolean value indicating whether the key was pressed or released.
  • A repeat count that can be greater than one when a key is held down.
  • The virtual-key code, identifying the given key in a device-independent manner.
  • The virtual-scan code, indicating the device-dependent value generated by the keyboard hardware.
  • The translated Unicode™ or ANSI character.
  • A flag variable indicating the state of the control keys (the ALT, CTRL, SHIFT, NUM LOCK, SCROLL LOCK, and CAPS LOCK keys) and indicating whether an enhanced key was pressed. Enhanced keys for the IBM® 101-key and 102-key keyboards are the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad and the divide (/) and ENTER keys in the numeric keypad.

Mouse Events

Mouse events are generated whenever the user moves the mouse or presses or releases one of the mouse buttons. Mouse events are placed in the input buffer only if the following conditions are met:

  • The console input mode is set to ENABLE_MOUSE_INPUT (the default mode).
  • The console window has the keyboard focus.
  • The mouse pointer is within the borders of the console's window.

If the input event is a mouse event, the Event member in INPUT_RECORD is a MOUSE_EVENT_RECORD structure containing the following information:

  • The coordinates of the mouse pointer in terms of the character-cell row and column in the screen buffer's coordinate system.
  • A flag variable indicating the state of the mouse buttons.
  • A flag variable indicating the state of the control keys (ALT, CTRL, SHIFT, NUM LOCK, SCROLL LOCK, and CAPS LOCK) and indicating whether an enhanced key was pressed. Enhanced keys for the IBM 101-key and 102-key keyboards are the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad and the divide (/) and ENTER keys in the numeric keypad.
  • A flag variable indicating whether the event was a normal button-press or button-release event, a mouse movement event, or the second click of a double-click event.

Note The mouse position coordinates are in terms of the screen buffer, not the console window. The screen buffer may have been scrolled with respect to the window, so the upper left corner of the window is not necessarily the (0,0) coordinate of the screen buffer. To determine the coordinates of the mouse relative to the coordinate system of the window, subtract the window origin coordinates from the mouse position coordinates. Use the GetConsoleScreenBufferInfo function to determine the window origin coordinates.

The dwButtonState member of the MOUSE_EVENT_RECORD structure has a bit corresponding to each mouse button. The bit is 1 if the button is down and 0 if the button is up. A button-release event is detected by a 0 value for the dwEventFlags member of MOUSE_EVENT_RECORD and a change in a button's bit from 1 to 0. The GetNumberOfConsoleMouseButtons function retrieves the number of buttons on the mouse.

Buffer-Resizing Events

A console window's menu enables the user to change the size of the active screen buffer; this change generates a buffer-resizing event. Buffer-resizing events are placed in the input buffer if the console's input mode is set to ENABLE_WINDOW_INPUT (that is, the default mode is disabled).

If the input event is a buffer-resizing event, the Event member of INPUT_RECORD is a WINDOW_BUFFER_SIZE_RECORD structure containing the new size of the screen buffer, expressed in character-cell columns and rows.

If the user reduces the size of the screen buffer, any data in the discarded portion of the buffer is lost.

Changes to the screen buffer size as a result of application calls to the SetConsoleScreenBufferSize function are not generated as buffer-resizing events.


Console Screen Buffers

A screen buffer is a two-dimensional array of character and color data for output in a console window. A console can have multiple screen buffers. The active screen buffer is the one that is displayed on the screen.

The system creates a screen buffer whenever it creates a new console. A process can use the CreateConsoleScreenBuffer function to create additional screen buffers for its console. A new screen buffer is not active until its handle is specified in a call to the SetConsoleActiveScreenBuffer function. However, screen buffers can be accessed for reading and writing whether they are active or inactive.

Each screen buffer has its own two-dimensional array of character information records. The data for each character is stored in a CHAR_INFO structure that specifies the Unicode or ANSI character and the foreground and background colors in which that character is displayed.

A number of properties associated with a screen buffer can be set independently for each screen buffer. This means that changing the active screen buffer can have a dramatic effect on the appearance of the console window. The properties associated with a screen buffer include:

  • Screen buffer size, in character rows and columns.
  • Text attributes (foreground and background colors for displaying text to be written by the WriteFile or WriteConsole function).
  • Window size and location (the rectangular region of the screen buffer that is displayed in the console window).
  • Cursor position, appearance, and visibility.
  • Output modes (ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT). For more information about console output modes, see High-Level Console Modes.

When a screen buffer is created, it contains blanks. Its cursor is visible and positioned at the buffer's origin (0,0), and the window is positioned with its upper left corner at the buffer's origin. The size of the screen buffer, the window size, the text attributes, and the appearance of the cursor are determined by the user or by the system defaults. To retrieve the current values of the various properties associated with the screen buffer, use the GetConsoleScreenBufferInfo, GetConsoleCursorInfo, and GetConsoleMode functions.

Applications that change any of the screen buffer properties should either create their own screen buffer or save the state of the inherited screen buffer during startup and restore it at exit.


Window and Screen Buffer Size

The size of a screen buffer is expressed in terms of a coordinate grid based on character cells. The width is the number of character cells in each row, and the height is the number of rows. Associated with each screen buffer is a window that determines the size and location of the rectangular portion of the screen buffer displayed in the console window. A screen buffer's window is defined by specifying the character-cell coordinates of the upper left and lower right cells of the window's rectangle.

A screen buffer can be any size, limited only by available memory. The dimensions of a screen buffer's window cannot exceed the corresponding dimensions of either the screen buffer or the maximum window that can fit on the screen based on the current font size (controlled exclusively by the user).

The GetConsoleScreenBufferInfo function returns the following information about a screen buffer and its window:

  • The current size of the screen buffer
  • The current location of the window
  • The maximum size of the window given the current screen buffer size, the current font size, and the screen size

The GetLargestConsoleWindowSize function returns the maximum size of a console's window based on the current font and screen sizes. This size differs from the maximum window size returned by GetConsoleScreenBufferInfo in that the screen buffer size is ignored.

To change a screen buffer's size, use the SetConsoleScreenBufferSize function. This function fails if either dimension of the specified size is less than the corresponding dimension of the console's window.

To change the size or location of a screen buffer's window, use the SetConsoleWindowInfo function. This function fails if the specified window-corner coordinates exceed the limits of the screen buffer or the screen. Changing the window size of the active screen buffer changes the size of the console window displayed on the screen.

A process can change its console's input mode to enable window input so that the process is able to receive input when the user changes the screen buffer size. If an application enables window input, it can use GetConsoleScreenBufferInfo to retrieve window and screen buffer size at startup. This information can then be used to determine the way data is displayed in the window. If the user changes the screen buffer size, the application can respond by changing the way data is displayed. For example, an application can adjust the way text wraps at the end of the line if the number of characters per row changes. If an application does not enable window input, it must either use the inherited window and screen buffer sizes, or set them to the desired size during startup and restore the inherited sizes at exit. For additional information about window input mode, see Low-Level Console Modes.


Scrolling the Screen Buffer

The console window displays a portion of the active screen buffer. Each screen buffer maintains its own current window rectangle that specifies the coordinates of the upper left and lower right character cells to be displayed in the console window. To determine the current window rectangle of a screen buffer, use GetConsoleScreenBufferInfo. When a screen buffer is created, the upper left corner of its window is at the upper left corner of the screen buffer at (0,0).

The window rectangle can change to display different parts of the screen buffer. The window rectangle of a screen buffer can change in the following situations:

  • When SetConsoleWindowInfo is called to specify a new window rectangle, it scrolls the view of the screen buffer by changing the position of the window rectangle without changing the size of the window. For examples of scrolling the window's contents, see Scrolling a Screen Buffer's Window.

  • When using the WriteFile function to write to a screen buffer with wrap at end-of-line (EOL) output mode enabled, the window rectangle shifts automatically, so the cursor is always displayed.
  • When the SetConsoleCursorPosition function specifies a new cursor position that is outside the boundaries of the current window rectangle, the window rectangle shifts automatically to display the cursor.
  • When the user changes the size of the console window or uses the window's scroll bars, the window rectangle of the active screen buffer can change. This change is not reported as a window resizing event in the input buffer.

In each of these situations, the window rectangle shifts to display a different part of the screen buffer, but the contents of the screen buffer remain in the same position. The following situations can cause the screen buffer's contents to shift:

  • When the ScrollConsoleScreenBuffer function is called, a rectangular block is copied from one part of a screen buffer to another.
  • When using WriteFile to write to a screen buffer with wrap at EOL output mode enabled, the screen buffer's contents scroll automatically when the end of the screen buffer is encountered. This scrolling discards the top row of the screen buffer.

ScrollConsoleScreenBuffer specifies the screen buffer rectangle that is moved and the new upper left coordinates to which the rectangle is copied. This function can scroll a portion or the entire contents of the screen buffer.

The illustration shows a ScrollConsoleScreenBuffer operation that scrolls the entire contents of the screen buffer up by several rows. The contents of the top rows are discarded, and the bottom rows are filled with a specified character and color.

The effects of ScrollConsoleScreenBuffer can be limited by specifying an optional clipping rectangle so that the contents of the screen buffer outside the clipping rectangle are unchanged. The effect of clipping is to create a subwindow (the clipping rectangle) whose contents are scrolled without affecting the rest of the screen buffer. For an example that uses ScrollConsoleScreenBuffer, see Scrolling a Screen Buffer's Contents.

Cursor Appearance and Position

A screen buffer's cursor can be visible or hidden. When it is visible, its appearance can vary, ranging from from completely filling a character cell to appearing as a horizontal line at the bottom of the cell. To retrieve information about the appearance and visibility of the cursor, use the GetConsoleCursorInfo function. This function reports whether the cursor is visible and describes the appearance of the cursor as the percentage of a character cell that it fills. To set the appearance and visibility of the cursor, use the SetConsoleCursorInfo function.

Characters written by the high-level console I/O functions are written at the current cursor location, advancing the cursor to the next location. To determine the current cursor position in the coordinate system of a screen buffer, use GetConsoleScreenBufferInfo. You can use SetConsoleCursorPosition to set the cursor position and, thereby, control the placement of text that is written or echoed by the high-level I/O functions. If you move the cursor, text at the new cursor location is overwritten.

The position, appearance, and visibility of the cursor are set independently for each screen buffer.

Screen Buffer Color Attributes

Each screen buffer character cell stores the color attributes for the colors used in drawing the text and background of that cell. An application can set the color data for each character cell individually, storing the data in the Attributes member of the CHAR_INFO structure for each cell.

The current text attributes of each screen buffer determine the foreground (text) and background colors of characters subsequently written or echoed by the high-level functions. An application can use GetConsoleScreenBufferInfo to determine the current text attributes of a screen buffer and the SetConsoleTextAttribute function to set the text attributes. Changing a screen buffer's text attributes does not affect the display of characters previously written. These text attributes do not affect characters written by the low-level console I/O functions (such as the WriteConsoleOutput or WriteConsoleOutputCharacter function), which either explicitly specify the attributes for each cell that is written or leave the attributes unchanged at the written positions.

The following attribute constants are defined in the WINCON.H header file:

  • FOREGROUND_BLUE
  • FOREGROUND_GREEN
  • FOREGROUND_RED
  • FOREGROUND_INTENSITY
  • BACKGROUND_BLUE
  • BACKGROUND_GREEN
  • BACKGROUND_RED
  • BACKGROUND_INTENSITY

The foreground attributes specify the text color, and the background attributes specify the color used to fill the cell's background. An application can combine the constants to achieve different colors. For example, the following combination results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

If no background constant is specified, the background is black, and if no foreground constant is specified, the text is black. For example, the following combination produces black text on a white background.

BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED


Input and Output Methods

This overview describes two very different approaches to console I/O, the choice of which depends on how much flexibility and control an application needs. The high-level approach enables simple character stream I/O, but it limits access to a console's input and screen buffers. The low-level approach requires that developers write more code and choose among a greater range of functions, but it also gives an application more flexibility.

An application can use the file I/O functions, ReadFile and WriteFile, and the console functions, ReadConsole and WriteConsole, for high-level I/O that provides indirect access to a console's input and screen buffers. The high-level input functions filter and process the data in a console's input buffer to return input as a stream of characters, discarding mouse and buffer-resizing input. Similarly, the high-level output functions write a stream of characters that are displayed at the current cursor location in a screen buffer. An application controls the way these functions work by setting a console's I/O modes.

The low-level I/O functions provide direct access to a console's input and screen buffers, enabling an application to access mouse and buffer-resizing input events and extended information for keyboard events. Low-level output functions enable an application to read from or write to a specified number of consecutive character cells in a screen buffer, or to read or write to rectangular blocks of character cells at a specified location in a screen buffer. A console's input modes affect low-level input by enabling the application to determine whether mouse and buffer-resizing events are placed in the input buffer. A console's output modes have no effect on low-level output.

The high-level and low-level I/O methods are not mutually exclusive, and an application can use any combination of these functions. Typically, however, an application uses one approach or the other exclusively.

The sections that follow describe in detail the console modes and the high-level and low-level I/O functions.


Console Modes

Associated with each console input buffer is a set of input modes that affects input operations. Similarly, each console screen buffer has a set of output modes that affects output operations. The input modes can be divided into two groups: those that affect the high-level input functions and those that affect the low-level input functions. The output modes only affect applications that use the high-level output functions.

The GetConsoleMode function reports the current input mode of a console's input buffer or the current output mode of a screen buffer. The SetConsoleMode function sets the current mode of either a console input buffer or a screen buffer. If a console has multiple screen buffers, the output modes of each can be different. An application can change I/O modes at any time. For more information about the console modes that affect high-level and low-level I/O operations, see High-Level Console Modes and Low-Level Console Modes.


High-Level Console I/O

The high-level I/O functions provide a simple way to read a stream of characters from console input or to write a stream of characters to console output. A high-level read operation gets input characters from a console's input buffer and stores them in a specified buffer. A high-level write operation takes characters from a specified buffer and writes them to a screen buffer at the current cursor location, advancing the cursor as each character is written.

High-level I/O gives you a choice between the ReadFile and WriteFile functions and the ReadConsole and WriteConsole functions. They are identical, except for two important differences. The console functions support the use of either Unicode characters or the ANSI character set; the file I/O functions do not support Unicode. Also, the file I/O functions can be used to access files, pipes, and serial communications devices; the console functions can only be used with console handles. This distinction is important if an application relies on standard handles that may have been redirected.

When using either set of high-level functions, an application can control the text and background colors used to display characters subsequently written to a screen buffer. An application can also use the console modes that affect high-level console I/O to enable or disable the following properties:

  • Echoing of keyboard input to the active screen buffer
  • Line input, in which a read operation does not return until the ENTER key is pressed
  • Automatic processing of keyboard input to handle carriage returns, CTRL+C, and other input details
  • Automatic processing of output to handle line wrapping, carriage returns, backspaces, and other output details


High-Level Console Modes

The behavior of the high-level console functions is affected by the console input and output modes. All of the following console input modes are enabled for a console's input buffer when a console is created:

  • Line input mode
  • Processed input mode
  • Echo input mode

Both of the following console output modes are enabled for a console screen buffer when it is created:

  • Processed output mode
  • Wrapping at EOL output mode

All three input modes, along with processed output mode, are designed to work together. It is best to either enable or disable all of these modes as a group. When all are enabled, the application is said to be in "cooked" mode, which means that most of the processing is handled for the application. When all are disabled, the application is in "raw" mode, which means that input is unfiltered and any processing is left to the application.

An application can use the GetConsoleMode function to determine the current mode of a console's input buffer or screen buffer. You can enable or disable any of these modes by using the following values in the SetConsoleMode function. Note that setting the output mode of one screen buffer does not affect the output mode of other screen buffers.

Mode | Description
ENABLE_PROCESSED_INPUT | Used with a console input handle to cause the system to process any system editing or control key input rather than returning it as input in the read operation's buffer. If line input is also enabled, backspaces and carriage returns are handled correctly. A backspace causes the cursor to move back one space without affecting the character at the cursor position. A carriage return is converted to carriage return – linefeed character combination. If echo input mode is enabled and the output should reflect system editing, processed output must be enabled for the active screen buffer. If processed input is enabled, the CTRL+C key combination is passed on to the appropriate handler regardless of whether line input is enabled. For more information about control handlers, see Console Control Handlers.
ENABLE_LINE_INPUT | Used with a console input handle to cause the ReadFile and ReadConsole functions to return when the ENTER key is pressed. If line input mode is disabled, the functions return when one or more characters are available in the input buffer.
ENABLE_ECHO_INPUT | Used with a console input handle to cause keyboard input read by the ReadFile or ReadConsole function to be echoed to the active screen buffer. Characters are echoed only if the process that calls ReadFile or ReadConsole has an open handle to the active screen buffer. Echo mode cannot be enabled unless line input is also enabled. The output mode of the active screen buffer affects the way echoed input is displayed.
ENABLE_PROCESSED_OUTPUT | Used with a console screen buffer handle to cause the system to perform the appropriate action for ANSI control characters that are written to a screen buffer. The backspace, tab, bell, carriage return, and linefeed characters are processed. A tab character moves the cursor to the next tab stop, which occurs every eight characters. A bell character sounds a short tone.
ENABLE_WRAP_AT_EOL_OUTPUT | Used with a console screen buffer handle to cause the current output position (cursor position) to move to the first column in the next row (line) when the end of the current row is reached. If the bottom of the window region is reached, the window origin is moved down one row. This movement has the effect of scrolling the contents of the window up one row. If the bottom of the screen buffer is reached, the contents of the screen buffer are scrolled up one row, and the top row of the screen buffer is discarded. Windows NT/2000 or later: If this mode is disabled, the last character in the row is overwritten with any subsequent characters. Windows 95/98/Me: This mode cannot be disabled. Any attempt to disable it is ignored.


High-Level Console Input and Output Functions

The ReadFile and WriteFile functions, or the ReadConsole and WriteConsole functions, enable an application to read console input and write console output as a stream of characters. ReadConsole and WriteConsole behave exactly like ReadFile and WriteFile except that they can be used either as wide-character functions (in which text arguments must use Unicode) or as ANSI functions (in which text arguments must use characters from the Windows character set). Applications that need to maintain a single set of sources to support either Unicode or the ANSI character set should use ReadConsole and WriteConsole.

ReadConsole and WriteConsole can only be used with console handles; ReadFile and WriteFile can be used with other handles (such as files or pipes). ReadConsole and WriteConsole fail if used with a standard handle that has been redirected and is no longer a console handle.

To get keyboard input, a process can use ReadFile or ReadConsole with a handle to the console's input buffer, or it can use ReadFile to read input from a file or a pipe if STDIN has been redirected. These functions only return keyboard events that can be translated into ANSI characters (or Unicode characters in the case of ReadConsole). The input that can be returned includes control key combinations. The functions do not return keyboard events involving the function keys or arrow keys. Input events generated by mouse, window, focus, or menu input are discarded.

If line input mode is enabled (the default mode), ReadFile and ReadConsole do not return to the calling application until the ENTER key is pressed. If line input mode is disabled, the functions do not return until at least one character is available. In either mode, all available characters are read until either no more keys are available or the specified number of characters has been read. Unread characters are buffered until the next read operation. The functions report the total number of characters actually read. If echo input mode is enabled, characters read by these functions are written to the active screen buffer at the current cursor position.

A process can use WriteFile or WriteConsole to write to either an active or inactive screen buffer, or it can use WriteFile to write to a file or a pipe if STDOUT has been redirected. Processed output mode and wrap at EOL output mode control the way characters are written or echoed to a screen buffer.

Characters written by WriteFile or WriteConsole, or echoed by ReadFile or ReadConsole, are inserted in a screen buffer at the current cursor position. As each character is written, the cursor position advances to the next character cell; however, the behavior at the end of a row depends on the screen buffer's wrap at EOL output mode. An application can use the GetConsoleScreenBufferInfo function to determine the current cursor position and the SetConsoleCursorPosition function to set the cursor position.

For an example that uses the high-level console I/O functions, see Using the High-Level Input and Output Functions.


Low-Level Console I/O

The low-level console I/O functions expand an application's control over console I/O by enabling direct access to a console's input and screen buffers. These functions enable an application to perform the following tasks:

  • Receive input about mouse and buffer-resizing events
  • Receive extended information about keyboard input events
  • Write input records to the input buffer
  • Read input records without removing them from the input buffer
  • Determine the number of pending events in the input buffer
  • Flush the input buffer
  • Read and write strings of Unicode or ANSI characters at a specified location in a screen buffer
  • Read and write strings of text and background color attributes at a specified screen buffer location
  • Read and write rectangular blocks of character and color data at a specified screen buffer location
  • Write a single Unicode or ANSI character, or a text and background color attribute combination, to a specified number of consecutive cells beginning at a specified screen buffer location


Low-Level Console Modes

The types of input events reported in a console's input buffer depend on the console's mouse and window input modes. The console's processed input mode determines how the system handles the CTRL+C key combination. To set or retrieve the state of a console's input modes, an application can specify a console input buffer handle in a call to the SetConsoleMode or GetConsoleMode function. The following modes are used with console input handles.

Mode | Description
ENABLE_MOUSE_INPUT | Controls whether mouse events are reported in the input buffer. By default, mouse input is enabled and window input is disabled. Changing either of these modes affects only input that occurs after the mode is set; pending mouse or window events in the input buffer are not flushed. The mouse pointer is displayed regardless of the mouse mode.
ENABLE_WINDOW_INPUT | Controls whether buffer-resizing events are reported in the input buffer. By default, mouse input is enabled and window input is disabled. Changing either of these modes affects only input that occurs after the mode is set; pending mouse or window events in the input buffer are not flushed. The mouse pointer is displayed regardless of the mouse mode.
ENABLE_PROCESSED_INPUT | Controls the processing of input for applications using the high-level console I/O functions. However, if processed input mode is enabled, the CTRL+C key combination is not reported in the console's input buffer. Instead, it is passed on to the appropriate control handler function. For more information about control handlers, see Console Control Handlers.

The output modes of a screen buffer do not affect the behavior of the low-level output functions.


Low-Level Console Input Functions

A console's input buffer contains input records that can include information about keyboard, mouse, buffer-resizing, focus, and menu events. The low-level functions provide direct access to the input buffer, unlike the high-level functions that filter and process the input buffer's data, discarding all but keyboard input.

There are five low-level functions for accessing a console's input buffer:

  • ReadConsoleInput
  • PeekConsoleInput
  • GetNumberOfConsoleInputEvents
  • WriteConsoleInput
  • FlushConsoleInputBuffer

The ReadConsoleInput, PeekConsoleInput, and WriteConsoleInput functions use the INPUT_RECORD structure to read from or write to an input buffer.

Following are descriptions of the low-level console input functions.

Function | Description
ReadConsoleInput | Reads and removes input records from an input buffer. The function does not return until at least one record is available to be read. Then all available records are transferred to the buffer of the calling process until either no more records are available or the specified number of records has been read. Unread records remain in the input buffer for the next read operation. The function reports the total number of records that have been read. For an example that uses ReadConsoleInput, see Reading Input Buffer Events.
PeekConsoleInput | Reads without removing the pending input records in an input buffer. All available records up to the specified number are copied into the buffer of the calling process. If no records are available, the function returns immediately. The function reports the total number of records that have been read.
GetNumberOfConsoleInputEvents | Determines the number of unread input records in an input buffer.
WriteConsoleInput | Places input records into the input buffer behind any pending records in the buffer. The input buffer grows dynamically, if necessary, to hold as many records as are written. To use this function, the specified input buffer handle must have GENERIC_WRITE access.
FlushConsoleInputBuffer | Discards all unread events in the input buffer. To use this function, the specified input buffer handle must have GENERIC_WRITE access.

A thread of an application's process can perform a wait operation to wait for input to be available in an input buffer. To initiate a wait operation, specify a handle to the input buffer in a call to any of the wait functions. These functions can return when the state of one or more objects is signaled. The state of a console input handle becomes signaled when there are unread records in its input buffer. The state is reset to nonsignaled when the input buffer becomes empty. If there is no input available, the calling thread enters an efficient wait state, consuming very little processor time while waiting for the conditions of the wait operation to be satisfied.


Low-Level Console Output Functions

The low-level console output functions provide direct access to the character cells of a screen buffer. One set of functions reads from or writes to consecutive cells beginning at any location in the screen buffer. Another set of functions reads from or writes to rectangular blocks of cells.

The following functions read from or write to a specified number of consecutive character cells in a screen buffer, beginning with a specified cell.

Function | Description
ReadConsoleOutputCharacter | Copies a string of Unicode or ANSI characters from a screen buffer.
WriteConsoleOutputCharacter | Writes a string of Unicode or ANSI characters to a screen buffer.
ReadConsoleOutputAttribute | Copies a string of text and background color attributes from a screen buffer.
WriteConsoleOutputAttribute | Writes a string of text and background color attributes to a screen buffer.
FillConsoleOutputCharacter | Writes a single Unicode or ANSI character to a specified number of consecutive cells in a screen buffer.
FillConsoleOutputAttribute | Writes a text and background color attribute combination to a specified number of consecutive cells in a screen buffer.

For all of these functions, when the last cell of a row is encountered, reading or writing wraps around to the first cell of the next row. When the end of the last row of the screen buffer is encountered, the write functions discard all unwritten characters or attributes, and the read functions report the number of characters or attributes actually written.

The following functions read from or write to rectangular blocks of character cells at a specified location in a screen buffer.

Function | Description
ReadConsoleOutput | Copies character and color data from a specified block of screen buffer cells into a given block in a destination buffer.
WriteConsoleOutput | Writes character and color data to a specified block of screen buffer cells from a given block in a source buffer.

These functions treat screen buffers and source or destination buffers as two-dimensional arrays of CHAR_INFO structures (containing character and color attribute data for each cell). The functions specify the width and height, in character cells, of the source or destination buffer, and the pointer to the buffer is treated as a pointer to the origin cell (0,0) of the two-dimensional array. The functions use a SMALL_RECT structure to specify which rectangle to access in the screen buffer, and the coordinates of the upper left cell in the source or destination buffer determine the location of the corresponding rectangle in that buffer.

These functions automatically clip the specified screen buffer rectangle to fit within the boundaries of the screen buffer. For example, if the rectangle specifies lower right coordinates that are (column 100, row 50) and the screen buffer is only 80 columns wide, the coordinates are clipped so that they are (column 79, row 50). Similarly, this adjusted rectangle is again clipped to fit within the boundaries of the source or destination buffer. The screen buffer coordinates of the actual rectangle that was read from or written to are specified. For an example that uses these functions, see Reading and Writing Blocks of Characters and Attributes.

The illustration shows a ReadConsoleOutput operation where clipping occurs when the block is read from the screen buffer, and again when the block is copied into the destination buffer. The function reports the actual screen buffer rectangle that it copied from.


Console Code Pages

A code page is a mapping of 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

Associated with each console are two code pages: one for input and one for output. A console uses its input code page to translate keyboard input into the corresponding character value. It uses its output code page to translate the character values written by the various output functions into the images displayed in the console window. An application can use the SetConsoleCP and GetConsoleCP functions to set and retrieve a console's input code pages and the SetConsoleOutputCP and GetConsoleOutputCP functions to set and retrieve its output code pages.

The identifiers of the code pages available on the local computer are stored in the registry under the following key.

HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage

For information about using the registry functions to determine the available code pages, see Registry.


Console Control Handlers

Each console process has its own list of control handler functions that are called by the system when the process receives a CTRL+C, CTRL+BREAK, or CTRL+CLOSE signal. Initially, the list of control handlers for each process contains only a default handler function that calls the ExitProcess function. A console process can add or remove additional HandlerRoutine functions by calling the SetConsoleCtrlHandler function. This function does not affect the lists of control handlers for other processes. When a console process receives any of the control signals, it calls the handler functions on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

The function's dwCtrlType parameter identifies which control signal was received, and the return value indicates whether the signal was handled.

For an example of a control handler function, see Registering a Control Handler Function.


CTRL+C and CTRL+BREAK Signals

The CTRL+C and CTRL+BREAK key combinations receive special handling by console processes. By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input. By default, these signals are passed to all console processes that are attached to the console, causing the system to call the control handler function or functions associated with these processes. Detached processes (GUI processes or console processes started with the DETACHED_PROCESS or CREATE_NEW_CONSOLE flag) are not affected.

CTRL+BREAK is always treated as a signal, but an application can change the default CTRL+C behavior in two ways that prevent the handler functions from being called:

  • The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT input mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
  • Windows NT/2000 or later: When SetConsoleCtrlHandler is called with NULL and TRUE values for its parameters, the calling process ignores CTRL+C signals. Normal CTRL+C processing is restored by calling SetConsoleCtrlHandler with NULL and FALSE values. This attribute of ignoring or not ignoring CTRL+C signals is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.


CTRL+CLOSE Signal

The system generates a CTRL+CLOSE signal when the user closes a console. All processes attached to the console receive the signal, giving each process an opportunity to clean up before termination. When a process receives this signal, the handler function can take one of the following actions after performing any cleanup operations:

  • Call ExitProcess to terminate the process.
  • Return FALSE. If none of the registered handler functions returns TRUE, the default handler terminates the process.
  • Return TRUE. In this case, no other handler functions are called, and a pop-up dialog box asks the user whether to terminate the process. If the user chooses not to terminate the process, the system does not close the console until the process finally terminates.


Console Process Groups

When a process uses the CreateProcess function to create a new console process, it can specify the CREATE_NEW_PROCESS_GROUP flag to make the new process the root process of a console process group. The process group includes all processes that are descendants of the root process.

A process can use the GenerateConsoleCtrlEvent function to send a CTRL+C or CTRL+BREAK signal to all processes in a console process group. The signal is only received by those processes in the group that are attached to the same console as the process that called GenerateConsoleCtrlEvent.


Using the Console

  • Using the high-level input and output functions
  • Writing characters or colors to consecutive cells
  • Reading and writing blocks of characters and attributes
  • Reading input buffer events
  • Scrolling a screen buffer's window
  • Scrolling a screen buffer's contents
  • Registering a control handler function
  • Console application issues


Using the High-Level Input and Output Functions

The following example uses the high-level console I/O functions for console I/O. For more information about the high-level console I/O functions, see High-Level Console I/O.

The example assumes that the default I/O modes are in effect initially for the first calls to the ReadFile and WriteFile functions. Then the input mode is changed to turn off line input mode and echo input mode for the second calls to ReadFile and WriteFile. The SetConsoleTextAttribute function is used to set the colors in which subsequently written text will be displayed. Before exiting, the program restores the original console input mode and color attributes.

The example's NewLine function is used when line input mode is disabled. It handles carriage returns by moving the cursor position to the first cell of the next row. If the cursor is already in the last row of the screen buffer, the contents of the screen buffer are scrolled up one line. For an example that illustrates the use of the ScrollConsoleScreenBuffer function to scroll a screen buffer, see Scrolling a Screen Buffer's Contents.

#include <windows.h>

void NewLine(void);
void ScrollScreenBuffer(HANDLE, INT);

HANDLE hStdout, hStdin;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;

void main(void)
{
    LPSTR lpszPrompt1 = "Type something and press Enter:\n";
    LPSTR lpszPrompt2 = "Type any key: ";
    CHAR chBuffer[256];
    DWORD cRead, cWritten, fdwMode, fdwOldMode;
    WORD wOldColorAttrs;

    // Get handles to STDIN and STDOUT.

    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE ||
        hStdout == INVALID_HANDLE_VALUE)
    {
        MyErrorExit("GetStdHandle");
    }

    // Save the current text colors.

    if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
        MyErrorExit("GetConsoleScreenBufferInfo");

    wOldColorAttrs = csbiInfo.wAttributes;

    // Set the text attr. to draw red text on black background.

    if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED))
        MyErrorExit("SetConsoleTextAttribute");

    // Write to STDOUT and read from STDIN by using the default
    // modes. Input is echoed automatically, and ReadFile
    // does not return until a carriage return is typed.
    //
    // The default input modes are line, processed, and echo.
    // The default output modes are processed and wrap at EOL.

    while (1)
    {
        if (! WriteFile(
            hStdout,              // output handle
            lpszPrompt1,          // prompt string
            lstrlen(lpszPrompt1), // string length
            &cWritten,            // bytes written
            NULL) )               // not overlapped
        break;
        if (! ReadFile(
            hStdin,    // input handle
            chBuffer,  // buffer to read into
            255,       // size of buffer
            &cRead,    // actual bytes read
            NULL) )    // not overlapped
        break;
        if (chBuffer[0] == 'q') break;
    }

    // Turn off the line input mode, and echo the input mode.

    if (! GetConsoleMode(hStdin, &fdwOldMode))
        MyErrorExit("GetConsoleMode");

    fdwMode = fdwOldMode &
        ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
    if (! SetConsoleMode(hStdin, fdwMode))
        MyErrorExit("SetConsoleMode");

    // Prompt for input.

    if (! WriteFile(
        hStdout,              // output handle
        lpszPrompt2,          // prompt string
        lstrlen(lpszPrompt2), // string length
        &cWritten,            // bytes written
        NULL) )               // not overlapped
    MyErrorExit("WriteFile");

    // Without line and echo input modes, ReadFile returns
    // when any input is available. Carriage returns must
    // be handled, and WriteFile is used to echo input.

    while (1)
    {
        if (! ReadFile(hStdin, chBuffer, 1, &cRead, NULL))
            break;
        if (chBuffer[0] == '\r')
            NewLine();
        else if (! WriteFile(hStdout, chBuffer, cRead,
            &cWritten, NULL)) break;
        if (chBuffer[0] == 'q') break;
    }

    // Restore the original console mode.

    if (! SetConsoleMode(hStdin, fdwOldMode))
        MyErrorExit("SetConsoleMode");

    // Restore the original text colors.

    if (! SetConsoleTextAttribute(hStdout, wOldColorAttrs))
        MyErrorExit("SetConsoleTextAttribute");
}

// The NewLine function handles carriage returns when the processed
// input mode is disabled. It gets the current cursor position
// and resets it to the first cell of the next row.

void NewLine(void)
{
    if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
        MyErrorExit("GetConsoleScreenBufferInfo");
    csbiInfo.dwCursorPosition.X = 0;

    // If it is the last line in the screen buffer, scroll
    // the buffer up.

    if ((csbiInfo.dwSize.Y-1) == csbiInfo.dwCursorPosition.Y)
    {
        ScrollScreenBuffer(hStdout, 1);
    }

    // Otherwise, advance the cursor to the next line.

    else csbiInfo.dwCursorPosition.Y += 1;

    if (! SetConsoleCursorPosition(hStdout,
        csbiInfo.dwCursorPosition))
    {
        MyErrorExit("SetConsoleCursorPosition");
    }
}


Writing Characters or Colors to Consecutive Cells

Characters or color attributes can be written to specified character cells in a screen buffer. The following example uses the WriteConsoleOutputCharacter function to write a string of characters beginning at the upper left corner of a screen buffer. Then the example uses the WriteConsoleOutputAttribute function to write a string of color attributes to the first 51 cells of the same row. The coord parameter for both functions specifies the character cell in the screen buffer at which writing begins. The location in the console window where these characters or colors appear depends on the current window rectangle of the screen buffer. For additional information about the relationship between a screen buffer and its windows, see Window and Screen Buffer Size and Scrolling the Screen Buffer.

    HANDLE hOutput;
    LPTSTR lpszString = "Character String";
    DWORD cWritten;
    BOOL fSuccess;
    COORD coord;
    WORD wColors[3], wColor;
    CHAR chFillChar;

// Write a string of characters to a screen buffer.

    coord.X = 0;            // start at first cell
    coord.Y = 0;            //   of first row
    fSuccess = WriteConsoleOutputCharacter(
        hOutput,              // screen buffer handle
        lpszString,           // pointer to source string
        lstrlen(lpszString),  // length of string
        coord,                // first cell to write to
        &cWritten);           // actual number written
    if (! fSuccess)
        MyErrorExit("WriteConsoleOutputCharacter");

// Write a string of colors to a screen buffer.

    wColors[0] = BACKGROUND_RED;
    wColors[1] = BACKGROUND_RED |     // white background
                 BACKGROUND_GREEN |
                 BACKGROUND_BLUE;
    wColors[2] = BACKGROUND_BLUE;

    for (;fSuccess && coord.X < 50; coord.X += 3)
    {
        fSuccess = WriteConsoleOutputAttribute(
            hOutput,          // screen buffer handle
            wColors,          // pointer to source string
            3,                // length of string
            coord,            // first cell to write to
            &cWritten);       // actual number written
    }
    if (! fSuccess)
        MyErrorExit("WriteConsoleOutputAttribute");

The same character or color attribute can be written to a specified number of consecutive screen buffer cells beginning at a specified location. The following example uses the FillConsoleOutputCharacter function to clear a 80-by-50-character screen buffer, and then it uses the FillConsoleOutputAttribute function to set the color attributes of the same cells.

// Fill an 80-by-50-character screen buffer with the space character.

    coord.X = 0;            // start at first cell
    coord.Y = 0;            //   of first row
    chFillChar = ' ';

    fSuccess = FillConsoleOutputCharacter(
        hStdout,          // screen buffer handle
        chFillChar,       // fill with spaces
        80*50,            // number of cells to fill
        coord,            // first cell to write to
        &cWritten);       // actual number written

    if (! fSuccess)
        MyErrorExit("FillConsoleOutputCharacter");

// Set 80-by-50-character screen buffer colors to white text on red.

    wColor = BACKGROUND_RED |
             FOREGROUND_RED |
             FOREGROUND_GREEN |
             FOREGROUND_BLUE;

    fSuccess = FillConsoleOutputAttribute(
        hStdout,          // screen buffer handle
        wColor,           // color to fill with
        80*50,            // number of cells to fill
        coord,            // first cell to write to
        &cWritten);       // actual number written

    if (! fSuccess)
        MyErrorExit("FillConsoleOutputAttribute");


Reading and Writing Blocks of Characters and Attributes

The ReadConsoleOutput function copies a rectangular block of character and color attribute data from a console screen buffer into a destination buffer. The function treats the destination buffer as a two-dimensional array of CHAR_INFO structures. Similarly, the WriteConsoleOutput function copies a rectangular block of character and color attribute data from a source buffer to a console screen buffer. For more information about reading from or writing to rectangular blocks of screen buffer cells, see Input and Output Methods.

The following example uses the CreateConsoleScreenBuffer function to create a new screen buffer. After the SetConsoleActiveScreenBuffer function makes this the active screen buffer, a block of characters and color attributes is copied from the top two rows of the SDTOUT screen buffer into a temporary buffer. The data is then copied from the temporary buffer into the new active screen buffer. When the application is finished using the new screen buffer, it calls SetConsoleActiveScreenBuffer to restore the original STDOUT screen buffer.

#include <windows.h>

VOID main(void)
{
    HANDLE hStdout, hNewScreenBuffer;
    SMALL_RECT srctReadRect;
    SMALL_RECT srctWriteRect;
    CHAR_INFO chiBuffer[160]; // [2][80];
    COORD coordBufSize;
    COORD coordBufCoord;
    BOOL fSuccess;

    // Get a handle to the STDOUT screen buffer to copy from and
    // create a new screen buffer to copy to.

    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    hNewScreenBuffer = CreateConsoleScreenBuffer(
       GENERIC_READ |           // read/write access
       GENERIC_WRITE,
       0,                       // not shared
       NULL,                    // no security attributes
       CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE
       NULL);                   // reserved; must be NULL
    if (hStdout == INVALID_HANDLE_VALUE ||
            hNewScreenBuffer == INVALID_HANDLE_VALUE)
    {
        MyErrorExit("CreateConsoleScreenBuffer");
    }

    // Make the new screen buffer the active screen buffer.

    if (! SetConsoleActiveScreenBuffer(hNewScreenBuffer) )
        MyErrorExit("SetConsoleActiveScreenBuffer");

    // Set the source rectangle.

    srctReadRect.Top = 0;    // top left: row 0, col 0
    srctReadRect.Left = 0;
    srctReadRect.Bottom = 1; // bot. right: row 1, col 79
    srctReadRect.Right = 79;

    // The temporary buffer size is 2 rows x 80 columns.

    coordBufSize.Y = 2;
    coordBufSize.X = 80;

    // The top left destination cell of the temporary buffer is
    // row 0, col 0.

    coordBufCoord.X = 0;
    coordBufCoord.Y = 0;

    // Copy the block from the screen buffer to the temp. buffer.

    fSuccess = ReadConsoleOutput(
       hStdout,        // screen buffer to read from
       chiBuffer,      // buffer to copy into
       coordBufSize,   // col-row size of chiBuffer
       coordBufCoord,  // top left dest. cell in chiBuffer
       &srctReadRect); // screen buffer source rectangle
    if (! fSuccess)
        MyErrorExit("ReadConsoleOutput");

    // Set the destination rectangle.

    srctWriteRect.Top = 10;    // top lt: row 10, col 0
    srctWriteRect.Left = 0;
    srctWriteRect.Bottom = 11; // bot. rt: row 11, col 79
    srctWriteRect.Right = 79;

    // Copy from the temporary buffer to the new screen buffer.

    fSuccess = WriteConsoleOutput(
        hNewScreenBuffer, // screen buffer to write to
        chiBuffer,        // buffer to copy from
        coordBufSize,     // col-row size of chiBuffer
        coordBufCoord,    // top left src cell in chiBuffer
        &srctWriteRect);  // dest. screen buffer rectangle
    if (! fSuccess)
        MyErrorExit("WriteConsoleOutput");
    Sleep(10000);

    // Restore the original active screen buffer.

    if (! SetConsoleActiveScreenBuffer(hStdout))
        MyErrorExit("SetConsoleActiveScreenBuffer");

}


Reading Input Buffer Events

The ReadConsoleInput function can be used to directly access a console's input buffer. When a console is created, mouse input is enabled and window input is disabled. To ensure that the process receives all types of events, this example uses the SetConsoleMode function to enable window and mouse input. Then it goes into a loop that reads and handles console input events.

VOID MouseEventProc(MOUSE_EVENT_RECORD);
VOID ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD);
VOID KeyEventProc(KEY_EVENT_RECORD);
VOID GetInputEvents(VOID);

DWORD main(VOID)
{
    HANDLE hStdin;
    DWORD cNumRead, fdwMode, fdwSaveOldMode, i;
    INPUT_RECORD irInBuf[128];

    // Get the standard input handle.

    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE)
        MyErrorExit("GetStdHandle");

    // Save the current input mode, to be restored on exit.

    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )
        MyErrorExit("GetConsoleMode");

    // Enable the window and mouse input events.

    fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
    if (! SetConsoleMode(hStdin, fdwMode) )
        MyErrorExit("SetConsoleMode");

    // Loop to read and handle the input events.

    while (1)
    {

        // Wait for the events.

        if (! ReadConsoleInput(
                hStdin,      // input buffer handle
                irInBuf,     // buffer to read into
                128,         // size of read buffer
                &cNumRead) ) // number of records read
            MyErrorExit("ReadConsoleInput");

        // Dispatch the events to the appropriate handler.

        for (i = 0; i < cNumRead; i++)
        {
            switch(irInBuf[i].EventType)
            {
                case KEY_EVENT: // keyboard input
                    KeyEventProc(irInBuf[i].Event.KeyEvent);
                    break;

                case MOUSE_EVENT: // mouse input
                    MouseEventProc(irInBuf[i].Event.MouseEvent);
                    break;

                case WINDOW_BUFFER_SIZE_EVENT: // scrn buf. resizing
                    ResizeEventProc(
                        irInBuf[i].Event.WindowBufferSizeEvent);
                    break;

                case FOCUS_EVENT:  // disregard focus events

                case MENU_EVENT:   // disregard menu events
                    break;

                default:
                    MyErrorExit("unknown event type");
                    break;
            }
        }
    }

    return 0;
}


Scrolling a Screen Buffer's Window

The SetConsoleWindowInfo function can be used to scroll the contents of a screen buffer in the console window. This function can also change the window size. The function can either specify the new upper left and lower right corners of the screen buffer's window as absolute screen buffer coordinates or specify the changes from the current window coordinates. The function fails if the specified window coordinates are outside the boundaries of the screen buffer.

The following example scrolls the view of the screen buffer up one row by modifying the absolute window coordinates returned by the GetConsoleScreenBufferInfo function.

HANDLE hStdout;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
SMALL_RECT srctWindow;

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

// Get the current screen buffer size and window position.

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
    MyErrorExit("GetConsoleScreenBufferInfo");

// Set srctWindow to the current window size and location.

srctWindow = csbiInfo.srWindow;

// If window is not at the screen buffer top, move it up one line.

if ( srctWindow.Top > 0 )
{
    srctWindow.Top -= 1;      // move top up by one row
    srctWindow.Bottom -= 1;   // move bottom up by one row

    if (! SetConsoleWindowInfo(
               hStdout,      // screen buffer handle
               TRUE,         // absolute coordinates
               &srctWindow)) // specifies new location
        MyErrorExit("SetConsoleWindowInfo");
}

The same scrolling can be done by specifying changes in the window coordinates.

// Get the current screen buffer window position.

if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
    MyErrorExit("GetConsoleScreenBufferInfo");

// If window is not at the screen buffer top, move it up one line.

if (csbiInfo.srWindow.Top > 0)
{
    srctWindow.Top = -1;      // move top up by one row
    srctWindow.Bottom = -1;   // move bottom up by one row
    srctWindow.Left = 0;      // no change
    srctWindow.Right = 0;     // no change

    if (! SetConsoleWindowInfo(
               hStdout,      // screen buffer handle
               FALSE,        // deltas, not absolute
               &srctWindow)) // specifies new location
    {
        MyErrorExit("SetConsoleWindowInfo");
    }
}


Scrolling a Screen Buffer's Contents

The ScrollConsoleScreenBuffer function moves a block of character cells from one part of a screen buffer to another part of the same screen buffer. The function specifies the upper left and lower right cells of the source rectangle to be moved and the destination coordinates of the new location for the upper left cell. The character and color data in the source cells is moved to the new location, and any cells left empty by the move are filled in with a specified character and color. If a clipping rectangle is specified, the cells outside of it are left unchanged.

ScrollConsoleScreenBuffer can be used to delete a line by specifying coordinates of the first cell in the line as the destination coordinates and specifying a scrolling rectangle that includes all the rows below the line.

The following example shows the use of a clipping rectangle to scroll only the bottom 15 rows of the screen buffer. The rows in the specified rectangle are scrolled up one line at a time, and the top row of the block is discarded. The contents of the screen buffer outside the clipping rectangle are left unchanged.

HANDLE hStdout;
BOOL fSuccess;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
SMALL_RECT srctScrollRect, srctClipRect;
CHAR_INFO chiFill;
COORD coordDest;

hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

if (hStdout == INVALID_HANDLE_VALUE)
    MyErrorExit("GetStdHandle");

// Get the screen buffer size.

fSuccess = GetConsoleScreenBufferInfo(hStdout, &csbiInfo);

if (! fSuccess)
    MyErrorExit("GetConsoleScreenBufferInfo");

// The scrolling rectangle is the bottom 15 rows of the
// screen buffer.

srctScrollRect.Top = csbiInfo.dwSize.Y - 16;
srctScrollRect.Bottom = csbiInfo.dwSize.Y - 1;
srctScrollRect.Left = 0;
srctScrollRect.Right = csbiInfo.dwSize.X - 1;

// The destination for the scroll rectangle is one row up.

coordDest.X = 0;
coordDest.Y = csbiInfo.dwSize.Y - 17;

// The clipping rectangle is the same as the scrolling rectangle.
// The destination row is left unchanged.

srctClipRect = srctScrollRect;

// Fill the bottom row with green blanks.

chiFill.Attributes = BACKGROUND_GREEN | FOREGROUND_RED;
chiFill.Char.AsciiChar = ' ';

// Scroll up one line.

fSuccess = ScrollConsoleScreenBuffer(
    hStdout,         // screen buffer handle
    &srctScrollRect, // scrolling rectangle
    &srctClipRect,   // clipping rectangle
    coordDest,       // top left destination cell
    &chiFill);       // fill character and color


Registering a Control Handler Function

This section shows an example of the SetConsoleCtrlHandler function that is used to install a control handler.

When a CTRL+C signal is received, the control handler returns TRUE, indicating that it has handled the signal. Doing this prevents other control handlers from being called.

When a CTRL_CLOSE_EVENT signal is received, the control handler returns TRUE, causing the system to display a dialog box that gives the user the choice of terminating the process and closing the console or allowing the process to continue execution. If the user chooses not to terminate the process, the system closes the console when the process finally terminates.

When a CTRL+BREAK, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT signal is received, the control handler returns FALSE. Doing this causes the signal to be passed to the next control handler function. If no other control handlers have been registered or none of the registered handlers returns TRUE, the default handler will be used, resulting in the process being terminated.

BOOL CtrlHandler(DWORD fdwCtrlType)
{
    switch (fdwCtrlType)
    {
        // Handle the CTRL+C signal.

        case CTRL_C_EVENT:

            Beep(1000, 1000);
            return TRUE;

        // CTRL+CLOSE: confirm that the user wants to exit.

        case CTRL_CLOSE_EVENT:

            return TRUE;

        // Pass other signals to the next handler.

        case CTRL_BREAK_EVENT:

        case CTRL_LOGOFF_EVENT:

        case CTRL_SHUTDOWN_EVENT:

        default:

            return FALSE;
    }
}

void main(void)
{
    BOOL fSuccess;

    fSuccess = SetConsoleCtrlHandler(
        (PHANDLER_ROUTINE) CtrlHandler,  // handler function
        TRUE);                           // add to list
    if (! fSuccess)
        MyErrorExit("Could not set control handler");
}


Console Application Issues

The 8-bit console functions use the OEM code page. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by the other functions and vice versa. For example, if FindFirstFileA returns a string that contains certain extended ANSI characters, WriteConsoleA will not display the string properly.

The best long-term solution for a console application is to use Unicode. Barring that solution, a console application should use the SetFileApisToOEM function. That function changes relevant file functions so that they produce OEM character set strings rather than ANSI character set strings.

The following are the file functions:

_lopen | GetDriveType | LoadLibrary
CopyFile | GetFileAttributes | LoadLibraryEx
CreateDirectory | GetFullPathName | MoveFile
CreateFile | GetModuleFileName | MoveFileEx
CreateProcess | GetModuleHandle | OpenFile
DeleteFile | GetSystemDirectory | RemoveDirectory
FindFirstFile | GetTempFileName | SearchPath
FindNextFile | GetTempPath | SetCurrentDirectory
GetCurrentDirectory | GetVolumeInformation | SetFileAttributes
GetDiskFreeSpace | GetWindowsDirectory |

When dealing with command lines, a console application should obtain the command line in Unicode form and convert it to OEM form, using the relevant character-to-OEM functions. Note, also, that argv uses the ANSI character set.


Console Reference

The following elements are associated with accessing a console.

  • Console Functions
  • Console Structures


Console Functions

The following functions are used to access a console.

Function | Description
AllocConsole | Allocates a new console for the calling process.
CreateConsoleScreenBuffer | Creates a console screen buffer.
FillConsoleOutputAttribute | Sets the text and background color attributes for a specified number of character cells.
FillConsoleOutputCharacter | Writes a character to the screen buffer a specified number of times.
FlushConsoleInputBuffer | Flushes the console input buffer.
FreeConsole | Detaches the calling process from its console.
GenerateConsoleCtrlEvent | Sends a specified signal to a console process group that shares the console associated with the calling process.
GetConsoleCP | Retrieves the input code page used by the console associated with the calling process.
GetConsoleCursorInfo | Retrieves information about the size and visibility of the cursor for the specified console screen buffer.
GetConsoleMode | Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
GetConsoleOutputCP | Retrieves the output code page used by the console associated with the calling process.
GetConsoleScreenBufferInfo | Retrieves information about the specified console screen buffer.
GetConsoleTitle | Retrieves the title bar string for the current console window.
GetConsoleWindow | Retrieves the window handle used by the console associated with the calling process.
GetLargestConsoleWindowSize | Retrieves the size of the largest possible console window.
GetNumberOfConsoleInputEvents | Retrieves the number of unread input records in the console's input buffer.
GetNumberOfConsoleMouseButtons | Retrieves the number of buttons on the mouse used by the current console.
GetStdHandle | Retrieves a handle for the standard input, standard output, or standard error device.
HandlerRoutine | An application-defined function used with the SetConsoleCtrlHandler function.
PeekConsoleInput | Reads data from the specified console input buffer without removing it from the buffer.
ReadConsole | Reads character input from the console input buffer and removes it from the buffer.
ReadConsoleInput | Reads data from a console input buffer and removes it from the buffer.
ReadConsoleOutput | Reads character and color attribute data from a rectangular block of character cells in a console screen buffer.
ReadConsoleOutputAttribute | Copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer.
ReadConsoleOutputCharacter | Copies a number of characters from consecutive cells of a console screen buffer.
ScrollConsoleScreenBuffer | Moves a block of data in a screen buffer.
SetConsoleActiveScreenBuffer | Sets the specified screen buffer to be the currently displayed console screen buffer.
SetConsoleCP | Sets the input code page used by the console associated with the calling process.
SetConsoleCtrlHandler | Adds or removes an application-defined HandlerRoutine from the list of handler functions for the calling process.
SetConsoleCursorInfo | Sets the size and visibility of the cursor for the specified console screen buffer.
SetConsoleCursorPosition | Sets the cursor position in the specified console screen buffer.
SetConsoleMode | Sets the input mode of a console's input buffer or the output mode of a console screen buffer.
SetConsoleOutputCP | Sets the output code page used by the console associated with the calling process.
SetConsoleScreenBufferSize | Changes the size of the specified console screen buffer.
SetConsoleTextAttribute | Sets the foreground (text) and background color attributes of characters written to the screen buffer.
SetConsoleTitle | Sets the title bar string for the current console window.
SetConsoleWindowInfo | Sets the current size and position of a console screen buffer's window.
SetStdHandle | Sets the handle for the standard input, standard output, or standard error device.
WriteConsole | Writes a character string to a console screen buffer beginning at the current cursor location.
WriteConsoleInput | Writes data directly to the console input buffer.
WriteConsoleOutput | Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
WriteConsoleOutputAttribute | Copies a number of foreground and background color attributes to consecutive cells of a console screen buffer.
WriteConsoleOutputCharacter | Copies a number of characters to consecutive cells of a console screen buffer.


AllocConsole

The AllocConsole function allocates a new console for the calling process.

BOOL AllocConsole(void);

Parameters

This function has no parameters.

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

A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, and then it can call AllocConsole to create a new console. If the calling process creates a child process, the child inherits the new console.

AllocConsole also sets up standard input, standard output, and standard error handles for the new console. The standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles to the console's screen buffer. To retrieve these handles, use the GetStdHandle function.

This function is primarily used by graphics applications to create a console window. Graphics applications are initialized without a console. Console applications are normally initialized with a console, unless they are created as detached processes (by calling the CreateProcess function with the DETACHED_PROCESS flag).

For an example, see Reading and Writing Blocks of Characters and Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CreateProcess, FreeConsole, GetStdHandle


CreateConsoleScreenBuffer

The CreateConsoleScreenBuffer function creates a console screen buffer.

HANDLE CreateConsoleScreenBuffer(
  DWORD dwDesiredAccess,                            // access
  DWORD dwShareMode,                                // buffer share mode
  CONST LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD
  DWORD dwFlags,                                    // buffer type
  LPVOID lpScreenBufferData                         // reserved
);

Parameters

dwDesiredAccess
[in] Specifies the desired access to the console screen buffer. This parameter can be one or more of the following values.
Value | Meaning
GENERIC_READ | Requests read access to the console screen buffer, enabling the process to read data from the buffer.
GENERIC_WRITE | Requests write access to the console screen buffer, enabling the process to write data to the buffer.

dwShareMode
[in] Specifies how this console screen buffer can be shared. This parameter can be zero, indicating that the buffer cannot be shared, or it can be one or more of the following values.
Value | Meaning
FILE_SHARE_READ | Other open operations can be performed on the console screen buffer for read access.
FILE_SHARE_WRITE | Other open operations can be performed on the console screen buffer for write access.

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 or later: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new console screen buffer. If lpSecurityAttributes is NULL, the console screen buffer gets a default security descriptor.

dwFlags
[in] Specifies the type of console screen buffer to create. The only currently supported screen buffer type is CONSOLE_TEXTMODE_BUFFER.
lpScreenBufferData
[in] Reserved; should be NULL.

Return Values

If the function succeeds, the return value is a handle to the new console screen buffer.

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

Remarks

A console can have multiple screen buffers but only one active screen buffer. Inactive screen buffers can be accessed for reading and writing, but only the active screen buffer is displayed. To make the new screen buffer the active screen buffer, use the SetConsoleActiveScreenBuffer function.

The calling process can use the returned handle in any function that requires a handle to a console screen buffer, subject to the limitations of access specified by the dwDesiredAccess parameter.

The calling process can use the DuplicateHandle function to create a duplicate screen buffer handle that has different access or inheritability from the original handle. However, DuplicateHandle cannot be used to create a duplicate that is valid for a different process (except through inheritance).

To close the screen buffer handle, use the CloseHandle function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CloseHandle, DuplicateHandle, GetConsoleScreenBufferInfo, SECURITY_ATTRIBUTES, SetConsoleActiveScreenBuffer, SetConsoleScreenBufferSize


FillConsoleOutputAttribute

The FillConsoleOutputAttribute function sets the text and background color attributes for a specified number of character cells, beginning at the specified coordinates in a screen buffer.

BOOL FillConsoleOutputAttribute(
  HANDLE hConsoleOutput,          // handle to screen buffer
  WORD wAttribute,                // color attribute
  DWORD nLength,                  // number of cells
  COORD dwWriteCoord,             // first coordinates
  LPDWORD lpNumberOfAttrsWritten  // number of cells written
);

Parameters

hConsoleOutput
[in] Handle to a screen buffer. The handle must have GENERIC_WRITE access.
wAttribute
[in] Specifies the foreground and background color attributes to write to the screen buffer. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
nLength
[in] Specifies the number of character cells to be set to the specified color attributes.
dwWriteCoord
[in] Specifies a COORD structure containing the screen buffer coordinates of the first cell whose attributes are to be set.
lpNumberOfAttrsWritten
[out] Pointer to the variable that receives the number of character cells whose attributes were actually set.

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

If the number of character cells whose attributes are to be set extends beyond the end of the specified row in the screen buffer, the cells of the next row are set. If the number of cells to write to extends beyond the end of the screen buffer, the cells are written up to the end of the screen buffer.

The character values at the positions written to are not changed.

For an example, see Writing Characters or Colors to Consecutive Cells.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, FillConsoleOutputCharacter, SetConsoleTextAttribute, WriteConsoleOutputAttribute


FillConsoleOutputCharacter

The FillConsoleOutputCharacter function writes a character to the screen buffer a specified number of times, beginning at the specified coordinates.

BOOL FillConsoleOutputCharacter(
  HANDLE hConsoleOutput,          // handle to screen buffer
  TCHAR cCharacter,               // character
  DWORD nLength,                  // number of cells
  COORD dwWriteCoord,             // first coordinates
  LPDWORD lpNumberOfCharsWritten  // number of cells written
);

Parameters

hConsoleOutput
[in] Handle to a screen buffer. The handle must have GENERIC_WRITE access.
cCharacter
[in] Specifies the character to write to the screen buffer.
nLength
[in] Specifies the number of character cells to write the character to.
dwWriteCoord
[in] Specifies a COORD structure containing the screen buffer coordinates of the first cell to write the character to.
lpNumberOfCharsWritten
[out] Pointer to a variable that receives the number of characters actually written to the screen buffer.

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

If the number of characters to write to extends beyond the end of the specified row in the screen buffer, characters are written to the next row. If the number of characters to write to extends beyond the end of the screen buffer, the characters are written up to the end of the screen buffer.

The attribute values at the positions written are not changed.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Writing Characters or Colors to Consecutive Cells.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, FillConsoleOutputAttribute, SetConsoleCP, SetConsoleOutputCP, WriteConsoleOutputCharacter


FlushConsoleInputBuffer

The FlushConsoleInputBuffer function flushes the console input buffer. All input records currently in the input buffer are discarded.

BOOL FlushConsoleInputBuffer(
  HANDLE hConsoleInput   // handle to console input buffer
);

Parameters

hConsoleInput
[in] Handle to the console input buffer. The handle must have GENERIC_WRITE access.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetNumberOfConsoleInputEvents, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


FreeConsole

The FreeConsole function detaches the calling process from its console.

BOOL FreeConsole(VOID);

Parameters

This function has no parameters.

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

If other processes share the console, the console is not destroyed, but the calling process cannot refer to it.

A process can use FreeConsole to detach itself from its current console, and then it can call the AllocConsole function to create a new console.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, AllocConsole


GenerateConsoleCtrlEvent

The GenerateConsoleCtrlEvent function sends a specified signal to a console process group that shares the console associated with the calling process.

BOOL GenerateConsoleCtrlEvent(
  DWORD dwCtrlEvent,       // signal to generate
  DWORD dwProcessGroupId   // process group to get signal
);

Parameters

dwCtrlEvent
[in] Specifies the type of signal to generate. This parameter can be one of the following values.
Value | Meaning
CTRL_C_EVENT | Generates a CTRL+C signal.
CTRL_BREAK_EVENT | Generates a CTRL+BREAK signal.

dwProcessGroupId
[in] Specifies the identifier of the process group that receives the signal. A process group is created when the CREATE_NEW_PROCESS_GROUP flag is specified in a call to the CreateProcess function. The process identifier of the new process is also the process group identifier of a new process group. The process group includes all processes that are descendants of the root process. Only those processes in the group that share the same console as the calling process receive the signal. In other words, if a process in the group creates a new console, that process does not receive the signal, nor do its descendants.

If this parameter is zero, the signal is generated in all processes that share the console of the calling process.

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

GenerateConsoleCtrlEvent causes the control handler functions of processes in the target group to be called. All console processes have a default handler function that calls the ExitProcess function. A console process can use the SetConsoleCtrlHandler function to install or remove other handler functions.

SetConsoleCtrlHandler can also enable an inheritable attribute that causes the calling process to ignore CTRL+C signals. If GenerateConsoleCtrlEvent sends a CTRL+C signal to a process for which this attribute is enabled, the handler functions for that process are not called. CTRL+BREAK signals always cause the handler functions to be called.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CreateProcess, ExitProcess, SetConsoleCtrlHandler


GetConsoleCP

The GetConsoleCP function retrieves the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

Japanese and Korean Windows 95/98/Me: The GetConsoleCP function returns the VM code page, because the OEM code page can be either 437 or DBCS.

Windows 95/98/Me: On all language versions besides Japanese and Korean, GetConsoleCP returns the OEM code page.

UINT GetConsoleCP(VOID);

Parameters

This function has no parameters.

Return Values

The return value is a code that identifies the code page.

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To set a console's input code page, use the SetConsoleCP function. To set and query a console's output code page, use the SetConsoleOutputCP and GetConsoleOutputCP functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleOutputCP, SetConsoleCP, SetConsoleOutputCP


GetConsoleCursorInfo

The GetConsoleCursorInfo function retrieves information about the size and visibility of the cursor for the specified console screen buffer.

BOOL GetConsoleCursorInfo(
  HANDLE hConsoleOutput,                    // handle to screen buffer
  PCONSOLE_CURSOR_INFO lpConsoleCursorInfo  // cursor information
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
lpConsoleCursorInfo
[out] Pointer to a CONSOLE_CURSOR_INFO structure in which information about the console's cursor is returned.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CONSOLE_CURSOR_INFO, SetConsoleCursorInfo


GetConsoleMode

The GetConsoleMode function retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.

BOOL GetConsoleMode(
  HANDLE hConsoleHandle,  // handle to console input or screen buffer
  LPDWORD lpMode          // current mode flags
);

Parameters

hConsoleHandle
[in] Handle to a console input buffer or a screen buffer. The handle must have GENERIC_READ access.
lpMode
[out] Pointer to a variable that indicates the current mode of the specified buffer.

If the hConsoleHandle parameter is an input handle, the mode can be a combination of the following values. When a console is created, all input modes except ENABLE_WINDOW_INPUT are enabled by default.
Value | Meaning
ENABLE_LINE_INPUT | The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_ECHO_INPUT | Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
ENABLE_PROCESSED_INPUT | CTRL+C is processed by the system and is not placed in the input buffer. If the input buffer is being read by ReadFile or ReadConsole, other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and linefeed characters are handled by the system.
ENABLE_WINDOW_INPUT | User interactions that change the size of the console screen buffer are reported in the console's input buffer. Information about these events can be read from the input buffer by applications using the ReadConsoleInput function, but not by those using ReadFile or ReadConsole.
ENABLE_MOUSE_INPUT | If the mouse pointer is within the borders of the console window and the window has the keyboard focus, mouse events generated by mouse movement and button presses are placed in the input buffer. These events are discarded by ReadFile or ReadConsole, even when this mode is enabled.

If the hConsoleHandle parameter is a screen buffer handle, the mode can be a combination of the following values. When a screen buffer is created, both output modes are enabled by default.
Value | Meaning
ENABLE_PROCESSED_OUTPUT | Characters written by the WriteFile or WriteConsole function or echoed by the ReadFile or ReadConsole function are parsed for ASCII control sequences, and the correct action is performed. Backspace, tab, bell, carriage return, and linefeed characters are processed.
ENABLE_WRAP_AT_EOL_OUTPUT | When writing with WriteFile or WriteConsole or echoing with ReadFile or ReadConsole, the cursor moves to the beginning of the next row when it reaches the end of the current row. This causes the rows displayed in the console window to scroll up automatically when the cursor advances beyond the last row in the window. It also causes the contents of the screen buffer to scroll up (discarding the top row of the screen buffer) when the cursor advances beyond the last row in the screen buffer. If this mode is disabled, the last character in the row is overwritten with any subsequent characters.

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

A console consists of an input buffer and one or more screen buffers. The mode of a console buffer determines how the console behaves during input or output (I/O) operations. One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles. Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.

The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes that use ReadFile or ReadConsole to read from the console's input buffer. Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects ReadFile and ReadConsole users, except that it also determines whether CTRL+C input is reported in the input buffer (to be read by the ReadConsoleInput function) or is passed to a function defined by the application.

The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions involving window resizing and mouse actions are reported in the input buffer or discarded. These events can be read by ReadConsoleInput, but they are always filtered by ReadFile and ReadConsole.

The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes using ReadFile or ReadConsole and WriteFile or WriteConsole.

To change a console's I/O modes, call SetConsoleMode function.

For an example, see Reading Input Buffer Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ReadConsole, ReadConsoleInput, ReadFile, SetConsoleMode, WriteConsole, WriteFile


GetConsoleOutputCP

The GetConsoleOutputCP function retrieves the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

Japanese and Korean Windows 95/98/Me: The GetConsoleOutputCP function returns the VM code page, because the OEM code page can be either 437 or DBCS.

Windows 95/98/Me: On all language versions besides Japanese and Korean, GetConsoleOutputCP returns the OEM code page.

UINT GetConsoleOutputCP(VOID);

Parameters

This function has no parameters.

Return Values

The return value is a code that identifies the code page.

Remarks

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To set a console's output code page, use the SetConsoleOutputCP function. To set and query a console's input code page, use the SetConsoleCP and GetConsoleCP functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleCP, SetConsoleCP, SetConsoleOutputCP


GetConsoleScreenBufferInfo

The GetConsoleScreenBufferInfo function retrieves information about the specified console screen buffer.

BOOL GetConsoleScreenBufferInfo(
  HANDLE hConsoleOutput,                                // handle to screen buffer
  PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo // screen buffer information
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
lpConsoleScreenBufferInfo
[out] Pointer to a CONSOLE_SCREEN_BUFFER_INFO structure in which the screen buffer information is returned.

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

The rectangle returned in the srWindow member of the CONSOLE_SCREEN_BUFFER_INFO structure can be modified and then passed to the SetConsoleWindowInfo function to scroll the screen buffer in the window, to change the size of the window, or both.

All coordinates returned in the CONSOLE_SCREEN_BUFFER_INFO structure are in character-cell coordinates, where the origin (0, 0) is at the upper-left corner of the screen buffer.

For an example, see Scrolling a Screen Buffer's Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CONSOLE_SCREEN_BUFFER_INFO, GetLargestConsoleWindowSize, SetConsoleCursorPosition, SetConsoleScreenBufferSize, SetConsoleWindowInfo


GetConsoleTitle

The GetConsoleTitle function retrieves the title bar string for the current console window.

DWORD GetConsoleTitle(
  LPTSTR lpConsoleTitle,  // console title
  DWORD nSize             // size of title buffer
);

Parameters

lpConsoleTitle
[out] Pointer to a buffer that receives a null-terminated string containing the text that appears in the title bar of the console window.
nSize
[in] Specifies the size, in characters, of the buffer pointed to by the lpConsoleTitle parameter.

Return Values

If the function succeeds, the return value is the length, in characters, of the string copied to the buffer.

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

Remarks

To set the title bar string for a console window, use the SetConsoleTitle function.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, SetConsoleCP, SetConsoleOutputCP, SetConsoleTitle


GetConsoleWindow

The GetConsoleWindow function retrieves the window handle used by the console associated with the calling process.

Note Although this function was implemented in Windows 2000, it was not included in the version of Wincon.h that was included with the Platform SDK for Windows 2000. To use this function on Windows 2000, use the prototype included in this documentation, and dynamically link to the function in Kernel32.dll.

HWND GetConsoleWindow (VOID);

Parameters

This function has no parameters.

Return Values

The return value is a handle to the window used by the console associated with the calling process or NULL if there is no such associated console.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character Support Overview, Console Functions


GetLargestConsoleWindowSize

The GetLargestConsoleWindowSize function retrieves the size of the largest possible console window, based on the current font and the size of the display.

COORD GetLargestConsoleWindowSize(
  HANDLE hConsoleOutput   // handle to screen buffer
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer.

Return Values

If the function succeeds, the return value is a COORD structure that specifies the number of character cell rows (X member) and columns (Y member) in the largest possible console window. Otherwise, the members of the structure are zero.

To get extended error information, call GetLastError.

Remarks

The function does not take into consideration the size of the screen buffer, which means that the window size returned may be larger than the size of the screen buffer. The GetConsoleScreenBufferInfo function can be used to determine the maximum size of the console window, given the current screen buffer size, the current font, and the display size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, GetConsoleScreenBufferInfo, SetConsoleWindowInfo


GetNumberOfConsoleInputEvents

The GetNumberOfConsoleInputEvents function retrieves the number of unread input records in the console's input buffer.

BOOL GetNumberOfConsoleInputEvents(
  HANDLE hConsoleInput,       // handle to console input buffer
  LPDWORD lpcNumberOfEvents   // number of events
);

Parameters

hConsoleInput
[in] Handle to the console input buffer. The handle must have GENERIC_READ access.
lpcNumberOfEvents
[out] Pointer to a variable that receives the number of unread input records in the console's input buffer.

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

The GetNumberOfConsoleInputEvents function reports the total number of unread input records in the input buffer, including keyboard, mouse, and window-resizing input records. Processes using the ReadFile or ReadConsole function can only read keyboard input. Processes using the ReadConsoleInput function can read all types of input records.

A process can specify a console input buffer handle in one of the wait functions to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.

To read input records from a console input buffer without affecting the number of unread records, use the PeekConsoleInput function. To discard all unread records in a console's input buffer, use the FlushConsoleInputBuffer function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, FlushConsoleInputBuffer, PeekConsoleInput, ReadConsole, ReadConsoleInput, ReadFile


GetNumberOfConsoleMouseButtons

The GetNumberOfConsoleMouseButtons function retrieves the number of buttons on the mouse used by the current console.

BOOL GetNumberOfConsoleMouseButtons(
  LPDWORD lpNumberOfMouseButtons   // number of buttons
);

Parameters

lpNumberOfMouseButtons
[in] Pointer to a variable that receives the number of mouse buttons.

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

When a console receives mouse input, an INPUT_RECORD structure containing a MOUSE_EVENT_RECORD structure is placed in the console's input buffer. The dwButtonState member of MOUSE_EVENT_RECORD has a bit indicating the state of each mouse button. The bit is 1 if the button is down and 0 if the button is up. To determine the number of bits that are significant, use GetNumberOfConsoleMouseButtons.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ReadConsoleInput, INPUT_RECORD, MOUSE_EVENT_RECORD


GetStdHandle

The GetStdHandle function retrieves a handle for the standard input, standard output, or standard error device.

HANDLE GetStdHandle(
  DWORD nStdHandle   // input, output, or error device
);

Parameters

nStdHandle
[in] Specifies the standard device for which to return the handle. This parameter can be one of the following values.
Value | Meaning
STD_INPUT_HANDLE | Standard input handle
STD_OUTPUT_HANDLE | Standard output handle
STD_ERROR_HANDLE | Standard error handle

Return Values

If the function succeeds, the return value is a handle to the specified device.

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

Remarks

Handles returned by GetStdHandle can be used by applications that need to read from or write to the console. When a console is created, the standard input handle is a handle to the console's input buffer, and the standard output and standard error handles are handles of the console's active screen buffer. These handles can be used by the ReadFile and WriteFile functions, or by any of the console functions that access the console input buffer or a screen buffer (for example, the ReadConsoleInput, WriteConsole, or GetConsoleScreenBufferInfo functions).

All handles returned by this function have GENERIC_READ and GENERIC_WRITE access unless the SetStdHandle function has been used to set a standard handle to be some handle with a lesser access.

The standard handles of a process may be redirected by a call to SetStdHandle, in which case GetStdHandle returns the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle to a console's input buffer. Similarly, you can specify the CONOUT$ value to get a handle to a console's active screen buffer.

For an example, see Reading Input Buffer Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CreateFile, GetConsoleScreenBufferInfo, ReadConsoleInput, ReadFile, SetStdHandle, WriteConsole, WriteFile


HandlerRoutine

A HandlerRoutine function is an application-defined function used with the SetConsoleCtrlHandler function. A console process uses this function to handle control signals received by the process. The PHANDLER_ROUTINE type defines a pointer to this callback function. HandlerRoutine is a placeholder for the application-defined function name.

BOOL WINAPI HandlerRoutine(
  DWORD dwCtrlType   //  control signal type
);

Parameters

dwCtrlType
[in] Indicates the type of control signal received by the handler. This parameter can be one of the following values.
Signal | Description
CTRL_C_EVENT | A CTRL+C signal was received, either from keyboard input or from a signal generated by the GenerateConsoleCtrlEvent function.
CTRL_BREAK_EVENT | A CTRL+BREAK signal was received, either from keyboard input or from a signal generated by GenerateConsoleCtrlEvent.
CTRL_CLOSE_EVENT | A signal that the system sends to all processes attached to a console when the user closes the console (either by clicking Close on the console window's window menu, or by clicking the End Task button command from Task Manager).
CTRL_LOGOFF_EVENT | A signal that the system sends to all console processes when a user is logging off. This signal does not indicate which user is logging off, so no assumptions can be made.
CTRL_SHUTDOWN_EVENT A signal that the system sends to all console processes when the system is shutting down.

Note that this signal is received only by services. Interactive applications are terminated at logoff, so they are not present when the system sends this signal. Services also have their own notification mechanism for shutdown events. For more information, see Handler.

Return Values

If the function handles the control signal, it should return TRUE. If it returns FALSE, the next handler function in the list of handlers for this process is used.

Remarks

Each console process has its own list of HandlerRoutine functions. Initially, this list contains only a default handler function that calls ExitProcess. A console process adds or removes additional handler functions by calling the SetConsoleCtrlHandler function, which does not affect the list of handler functions for other processes. When a console process receives any of the control signals, its handler functions are called on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

The CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals give the process an opportunity to clean up before termination. A HandlerRoutine called to handle any of these signals can do one of the following after performing any cleanup operations:

  • Call the ExitProcess function to terminate the process.
  • Return FALSE. If none of the registered handler functions returns TRUE, the default handler terminates the process.
  • Return TRUE. In this case, no other handler functions are called, and the system displays a pop-up dialog box that asks the user whether to terminate the process. The system also displays the dialog box if the process does not respond within a certain time-out period (5 seconds for CTRL_CLOSE_EVENT, and 20 seconds for CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT).

A process can use the SetProcessShutdownParameters function to prevent the system from displaying the CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT dialog box to the user. In this case, the system terminates the process when HandlerRoutine returns TRUE or when the time-out period elapses.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ExitProcess, GenerateConsoleCtrlEvent, GetProcessShutdownParameters, SetConsoleCtrlHandler, SetProcessShutdownParameters


PeekConsoleInput

The PeekConsoleInput function reads data from the specified console input buffer without removing it from the buffer.

BOOL PeekConsoleInput(
  HANDLE hConsoleInput,         // handle to console input buffer
  PINPUT_RECORD lpBuffer,       // peek data
  DWORD nLength,                // number of records to read
  LPDWORD lpNumberOfEventsRead  // number of records read
);

Parameters

hConsoleInput
[in] Handle to the input buffer. The handle must have GENERIC_READ access.
lpBuffer
[out] Pointer to an INPUT_RECORD buffer that receives the input buffer data.
nLength
[in] Specifies the size, in records, of the buffer pointed to by the lpBuffer parameter.
lpNumberOfEventsRead
[out] Pointer to a variable that receives the number of input records read.

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

If the number of records requested exceeds the number of records available in the buffer, the number available is read. If no data is available, the function returns immediately.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, INPUT_RECORD, ReadConsoleInput, SetConsoleCP, SetConsoleOutputCP, WriteConsoleInput


ReadConsole

The ReadConsole function reads character input from the console input buffer and removes it from the buffer.

BOOL ReadConsole(
  HANDLE hConsoleInput,         // handle to console input buffer
  LPVOID lpBuffer,              // data buffer
  DWORD nNumberOfCharsToRead,   // number of characters to read
  LPDWORD lpNumberOfCharsRead,  // number of characters read
  LPVOID lpReserved             // reserved
);

Parameters

hConsoleInput
[in] Handle to the console input buffer. The handle must have GENERIC_READ access.
lpBuffer
[out] Pointer to a buffer that receives the data read from the console input buffer.
nNumberOfCharsToRead
[in] Specifies the number of TCHARs to read. Because the function can read either Unicode or ANSI characters, the size of the buffer pointed to by the lpBuffer parameter should be at least nNumberOfCharsToRead * sizeof(TCHAR) bytes.
lpNumberOfCharsRead
[out] Pointer to a variable that receives the number of TCHARs actually read.
lpReserved
[in] Reserved; must be NULL.

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

ReadConsole reads keyboard input from a console's input buffer. It behaves like the ReadFile function, except that it can read in either Unicode (wide-character) or ANSI mode. To have applications that maintain a single set of sources compatible with both modes, use ReadConsole rather than ReadFile. Although ReadConsole can only be used with a console input buffer handle, ReadFile can be used with other handles (such as files or pipes). ReadConsole fails if used with a standard handle that has been redirected to be something other than a console handle.

All of the input modes that affect the behavior of ReadFile have the same effect on ReadConsole. To retrieve and set the input modes of a console input buffer, use the GetConsoleMode and SetConsoleMode functions.

If the input buffer contains input events other than keyboard events (such as mouse events or window-resizing events), they are discarded. Those events can only be read by using the ReadConsoleInput function.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleMode, ReadConsoleInput, ReadFile, SetConsoleCP, SetConsoleMode, SetConsoleOutputCP, WriteConsole


ReadConsoleInput

The ReadConsoleInput function reads data from a console input buffer and removes it from the buffer.

BOOL ReadConsoleInput(
  HANDLE hConsoleInput,         // handle to console input buffer
  PINPUT_RECORD lpBuffer,       // data buffer
  DWORD nLength,                // number of records to read
  LPDWORD lpNumberOfEventsRead  // number of records read
);

Parameters

hConsoleInput
[in] Handle to the input buffer. The handle must have GENERIC_READ access.
lpBuffer
[out] Pointer to an INPUT_RECORD buffer that receives the input buffer data.
nLength
[in] Specifies the size, in input records, of the buffer pointed to by the lpBuffer parameter.
lpNumberOfEventsRead
[out] Pointer to a variable that receives the number of input records read.

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

If the number of records requested in the nLength parameter exceeds the number of records available in the buffer, the number available is read. The function does not return until at least one input record has been read.

A process can specify a console input buffer handle in one of the wait functions to determine when there is unread console input. When the input buffer is not empty, the state of a console input buffer handle is signaled.

To determine the number of unread input records in a console's input buffer, use the GetNumberOfConsoleInputEvents function. To read input records from a console input buffer without affecting the number of unread records, use the PeekConsoleInput function. To discard all unread records in a console's input buffer, use the FlushConsoleInputBuffer function.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Reading Input Buffer Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, FlushConsoleInputBuffer, GetNumberOfConsoleInputEvents, INPUT_RECORD, PeekConsoleInput, ReadConsole, ReadFile, SetConsoleCP, SetConsoleOutputCP, WriteConsoleInput


ReadConsoleOutput

The ReadConsoleOutput function reads character and color attribute data from a rectangular block of character cells in a console screen buffer, and the function writes the data to a rectangular block at a specified location in the destination buffer.

BOOL ReadConsoleOutput(
  HANDLE hConsoleOutput,     // handle to screen buffer
  PCHAR_INFO lpBuffer,       // data buffer
  COORD dwBufferSize,        // column-row size of buffer
  COORD dwBufferCoord,       // upper-left cell to write
  PSMALL_RECT lpReadRegion   // read rectangle
);

Parameters

hConsoleOutput
[in] Handle to the screen buffer. The handle must have GENERIC_READ access.
lpBuffer
[out] Pointer to a destination buffer that receives the data read from the screen buffer. This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the dwBufferSize parameter.
dwBufferSize
[in] Specifies the size, in character cells, of the lpBuffer parameter. The X member of the COORD structure is the number of columns; the Y member is the number of rows.
dwBufferCoord
[in] Specifies the coordinates of the upper-left cell in the lpBuffer parameter that receives the data read from the screen buffer. The X member of the COORD structure is the column, and the Y member is the row.
lpReadRegion
[in/out] Pointer to a SMALL_RECT structure. On input, the structure members specify the upper-left and lower-right coordinates of the screen buffer rectangle from which the function is to read. On output, the structure members specify the actual rectangle that the function copied from.

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

ReadConsoleOutput treats the screen buffer and the destination buffer as two-dimensional arrays (columns and rows of character cells). The rectangle pointed to by the lpReadRegion parameter specifies the size and location of the block to be read from the screen buffer. A destination rectangle of the same size is located with its upper-left cell at the coordinates of the dwBufferCoord parameter in the lpBuffer array. Data read from the cells in the screen buffer source rectangle is copied to the corresponding cells in the destination buffer. If the corresponding cell is outside the boundaries of the destination buffer rectangle (whose dimensions are specified by the dwBufferSize parameter), the data is not copied.

Cells in the destination buffer corresponding to coordinates that are not within the boundaries of the screen buffer are left unchanged. In other words, these are the cells for which no screen buffer data is available to be read.

Before ReadConsoleOutput returns, it sets the members of the structure pointed to by the lpReadRegion parameter to the actual screen buffer rectangle whose cells were copied into the destination buffer. This rectangle reflects the cells in the source rectangle for which there existed a corresponding cell in the destination buffer, because ReadConsoleOutput clips the dimensions of the source rectangle to fit the boundaries of the screen buffer.

If the rectangle specified by lpReadRegion lies completely outside the boundaries of the screen buffer, or if the corresponding rectangle is positioned completely outside the boundaries of the destination buffer, no data is copied. In this case, the function returns with the members of the structure pointed to by the lpReadRegion parameter set such that the Right member is less than the Left, or the Bottom member is less than the Top. To determine the size of the screen buffer, use the GetConsoleScreenBufferInfo function.

The ReadConsoleOutput function has no effect on the screen buffer's cursor position. The contents of the screen buffer are not changed by the function.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Reading and Writing Blocks of Characters and Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CHAR_INFO, COORD, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, SetConsoleCP, SetConsoleOutputCP, SMALL_RECT, WriteConsoleOutput


ReadConsoleOutputAttribute

The ReadConsoleOutputAttribute function copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer, beginning at a specified location.

BOOL ReadConsoleOutputAttribute(
  HANDLE hConsoleOutput,       // handle to screen buffer
  LPWORD lpAttribute,          // attributes buffer
  DWORD nLength,               // number of cells to read
  COORD dwReadCoord,           // coordinates of first cell
  LPDWORD lpNumberOfAttrsRead  // number of cells read
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
lpAttribute
[out] Pointer to a buffer that receives the attributes read from the screen buffer.
nLength
[in] Specifies the number of screen buffer character cells from which to read. The size of the buffer pointed to by the lpAttribute parameter should be nLength * sizeof(WORD).
dwReadCoord
[in] Specifies the coordinates of the first cell in the screen buffer from which to read. The X member of the COORD structure is the column, and the Y member is the row.
lpNumberOfAttrsRead
[out] Pointer to a variable that receives the number of attributes actually read.

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

If the number of attributes to be read from extends beyond the end of the specified screen buffer row, attributes are read from the next row. If the number of attributes to be read from extends beyond the end of the screen buffer, attributes up to the end of the screen buffer are read.

Each attribute specifies the foreground (text) and background colors in which that character cell is drawn. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:

FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, ReadConsoleOutput, ReadConsoleOutputCharacter, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


ReadConsoleOutputCharacter

The ReadConsoleOutputCharacter function copies a number of characters from consecutive cells of a console screen buffer, beginning at a specified location.

BOOL ReadConsoleOutputCharacter(
  HANDLE hConsoleOutput,       // handle to screen buffer
  LPTSTR lpCharacter,          // character buffer
  DWORD nLength,               // number of cells to read
  COORD dwReadCoord,           // coordinates of first cell
  LPDWORD lpNumberOfCharsRead  // number of cells read
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
lpCharacter
[out] Pointer to a buffer that receives the characters read from the screen buffer.
nLength
[in] Specifies the number of screen buffer character cells from which to read. The size of the buffer pointed to by the lpCharacter parameter should be nLength * sizeof(TCHAR).
dwReadCoord
[in] Specifies the coordinates of the first cell in the screen buffer from which to read. The X member of the COORD structure is the column, and the Y member is the row.
lpNumberOfCharsRead
[out] Pointer to a variable that receives the number of characters actually read.

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

If the number of characters to be read from extends beyond the end of the specified screen buffer row, characters are read from the next row. If the number of characters to be read from extends beyond the end of the screen buffer, characters up to the end of the screen buffer are read.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, ReadConsoleOutput, ReadConsoleOutputAttribute, SetConsoleCP, SetConsoleOutputCP, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


ScrollConsoleScreenBuffer

The ScrollConsoleScreenBuffer function moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the screen buffer outside the clipping rectangle are unchanged.

BOOL ScrollConsoleScreenBuffer(
  HANDLE hConsoleOutput,               // handle to screen buffer
  CONST SMALL_RECT* lpScrollRectangle, // scroll rectangle
  CONST SMALL_RECT* lpClipRectangle,   // clipping rectangle
  COORD dwDestinationOrigin,           // new location
  CONST CHAR_INFO* lpFill              // fill character and color
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
lpScrollRectangle
[in] Pointer to a SMALL_RECT structure whose members specify the upper-left and lower-right coordinates of the screen buffer rectangle to be moved.
lpClipRectangle
[in] Pointer to a SMALL_RECT structure whose members specify the upper-left and lower-right coordinates of the screen buffer rectangle that is affected by the scrolling. This pointer can be NULL.
dwDestinationOrigin
[in] Specifies the upper-left corner of the new location of the lpScrollRectangle contents.
lpFill
[in] Pointer to a CHAR_INFO structure that specifies the character and color attributes to be used in filling the cells within the intersection of lpScrollRectangle and lpClipRectangle that were left empty as a result of the move.

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

ScrollConsoleScreenBuffer copies the contents of a rectangular region of a screen buffer, specified by the lpScrollRectangle parameter, to another area of the screen buffer. The target rectangle has the same dimensions as the lpScrollRectangle rectangle with its upper-left corner at the coordinates specified by the dwDestinationOrigin parameter. Those parts of lpScrollRectangle that do not overlap with the target rectangle are filled in with the character and color attributes specified by the lpFill parameter.

The clipping rectangle applies to changes made in both the lpScrollRectangle rectangle and the target rectangle. For example, if the clipping rectangle does not include a region that would have been filled by the contents of lpFill, the original contents of the region are left unchanged.

If the scroll or target regions extend beyond the dimensions of the screen buffer, they are clipped. For example, if lpScrollRectangle is the region contained by (0,0) and (19,19) and dwDestinationOrigin is (10,15), the target rectangle is the region contained by (10,15) and (29,34). However, if the screen buffer is 50 characters wide and 30 characters high, the target rectangle is clipped to (10,15) and (29,29). Changes to the screen buffer are also clipped according to lpClipRectangle, if the parameter specifies a SMALL_RECT structure. If the clipping rectangle is specified as (0,0) and (49,19), only the changes that occur in that region of the screen buffer are made.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Scrolling a Screen Buffer's Contents.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CHAR_INFO, SetConsoleCP, SetConsoleOutputCP, SetConsoleWindowInfo, SMALL_RECT


SetConsoleActiveScreenBuffer

The SetConsoleActiveScreenBuffer function sets the specified screen buffer to be the currently displayed console screen buffer.

BOOL SetConsoleActiveScreenBuffer(
  HANDLE hConsoleOutput   // handle to screen buffer
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer.

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

A console can have multiple screen buffers. SetConsoleActiveScreenBuffer determines which one is displayed. You can write to an inactive screen buffer and then use SetConsoleActiveScreenBuffer to display the buffer's contents.

For an example, see Reading and Writing Blocks of Characters and Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CreateConsoleScreenBuffer


SetConsoleCP

The SetConsoleCP function sets the input code page used by the console associated with the calling process. A console uses its input code page to translate keyboard input into the corresponding character value.

BOOL SetConsoleCP(
  UINT wCodePageID   // code page
);

Parameters

wCodePageID
[in] Specifies the identifier of the code page to set. The identifiers of the code pages available on the local computer are stored in the registry under the following key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage

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

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To determine a console's current input code page, use the GetConsoleCP function. To set and retrieve a console's output code page, use the SetConsoleOutputCP and GetConsoleOutputCP functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleCP, GetConsoleOutputCP, SetConsoleOutputCP


SetConsoleCtrlHandler

The SetConsoleCtrlHandler function adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process.

Windows NT/2000 or later: If no handler function is specified, the function sets an inheritable attribute that determines whether the calling process ignores CTRL+C signals.

BOOL SetConsoleCtrlHandler(
  PHANDLER_ROUTINE HandlerRoutine,  // handler function
  BOOL Add                          // add or remove handler
);

Parameters

HandlerRoutine
[in] Pointer to the application-defined HandlerRoutine function to add or remove.

Windows NT/2000 or later: This parameter can be NULL.

Add
[in] Specifies whether to add or remove the function pointed to by the HandlerRoutine parameter from the handler list. If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.

Windows NT/2000 or later: If the HandlerRoutine parameter is NULL, a TRUE value causes the calling process to ignore CTRL+C input, and a FALSE value restores normal processing of CTRL+C input. This attribute of ignoring or processing CTRL+C is inherited by child processes.

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

Each console process has its own list of application-defined HandlerRoutine functions that handle CTRL+C and CTRL+BREAK signals. The handler functions also handle signals generated by the system when the user closes the console, logs off, or shuts down the system. Initially, the handler list for each process contains only a default handler function that calls the ExitProcess function. A console process adds or removes additional handler functions by calling the SetConsoleCtrlHandler function, which does not affect the list of handler functions for other processes. When a console process receives any of the control signals, its handler functions are called on a last-registered, first-called basis until one of the handlers returns TRUE. If none of the handlers returns TRUE, the default handler is called.

For console processes, the CTRL+C and CTRL+BREAK key combinations are typically treated as signals (CTRL_C_EVENT and CTRL_C_BREAK_EVENT). When a console window with the keyboard focus receives CTRL+C or CTRL+BREAK, the signal is typically passed to all processes sharing that console.

CTRL+BREAK is always treated as a signal, but typical CTRL+C behavior can be changed in three ways that prevent the handler functions from being called:

  • The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
  • Windows NT/2000 or later: Calling SetConsoleCtrlHandler with the NULL and TRUE arguments causes the calling process to ignore CTRL+C signals. This attribute is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.
  • If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This exception is raised only for the benefit of the debugger, and an application should never use an exception handler to deal with it. If the debugger handles the exception, an application will not notice the CTRL+C, with one exception: alertable waits will terminate. If the debugger passes the exception on unhandled, CTRL+C is passed to the console process and treated as a signal, as previously discussed.

A console process can use the GenerateConsoleCtrlEvent function to send a CTRL+C or CTRL+BREAK signal to a console process group.

The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. Console functions, or any C run-time functions that call console functions, may not work reliably during processing of any of the three signals mentioned previously. The reason is that some or all of the internal console cleanup routines may have been called before executing the process signal handler.

For an example, see Registering a Control Handler Function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ExitProcess, GenerateConsoleCtrlEvent, GetConsoleMode, HandlerRoutine, SetConsoleMode


SetConsoleCursorInfo

The SetConsoleCursorInfo function sets the size and visibility of the cursor for the specified console screen buffer.

BOOL SetConsoleCursorInfo(
  HANDLE hConsoleOutput,                         // handle to screen buffer
  CONST CONSOLE_CURSOR_INFO *lpConsoleCursorInfo // cursor information
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
lpConsoleCursorInfo
[in] Pointer to a CONSOLE_CURSOR_INFO structure containing the new specifications for the screen buffer's cursor.

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

When a screen buffer's cursor is visible, its appearance can vary, ranging from completely filling a character cell to showing up as a horizontal line at the bottom of the cell. The dwSize member of the CONSOLE_CURSOR_INFO structure specifies the percentage of a character cell that is filled by the cursor. If this member is less than 1 or greater than 100, SetConsoleCursorInfo fails.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CONSOLE_CURSOR_INFO, GetConsoleCursorInfo, SetConsoleCursorPosition


SetConsoleCursorPosition

The SetConsoleCursorPosition function sets the cursor position in the specified console screen buffer.

BOOL SetConsoleCursorPosition(
  HANDLE hConsoleOutput,  // handle to screen buffer
  COORD dwCursorPosition  // new cursor coordinates
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
dwCursorPosition
[in] Specifies a COORD structure containing the new cursor position. The coordinates are the column and row of a screen buffer character cell. The coordinates must be within the boundaries of the screen buffer.

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

The cursor position determines where characters written by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function, are displayed. To determine the current position of the cursor, use the GetConsoleScreenBufferInfo function.

If the new cursor position is not within the boundaries of the screen buffer's window, the window origin changes to make the cursor visible.

For an example, see Using the High-Level Input and Output Functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleCursorInfo, GetConsoleScreenBufferInfo, ReadConsole, ReadFile, SetConsoleCursorInfo, WriteConsole, WriteFile


SetConsoleMode

The SetConsoleMode function sets the input mode of a console's input buffer or the output mode of a console screen buffer.

BOOL SetConsoleMode(
  HANDLE hConsoleHandle,  // handle to console input or screen buffer
  DWORD dwMode            // input or output mode
);

Parameters

hConsoleHandle
[in] Handle to a console input buffer or a screen buffer. The handle must have GENERIC_WRITE access.
dwMode
[in] Specifies the input or output mode to set. If the hConsoleHandle parameter is an input handle, the mode can be a combination of the following values. When a console is created, all input modes except ENABLE_WINDOW_INPUT are enabled by default.
Value | Meaning
ENABLE_LINE_INPUT | The ReadFile or ReadConsole function returns only when a carriage return character is read. If this mode is disabled, the functions return when one or more characters are available.
ENABLE_ECHO_INPUT | Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read. This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
ENABLE_PROCESSED_INPUT | CTRL+C is processed by the system and is not placed in the input buffer. If the input buffer is being read by ReadFile or ReadConsole, other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and linefeed characters are handled by the system.
ENABLE_WINDOW_INPUT | User interactions that change the size of the console screen buffer are reported in the console's input buffer. Information about these events can be read from the input buffer by applications using the ReadConsoleInput function, but not by those using ReadFile or ReadConsole.
ENABLE_MOUSE_INPUT | If the mouse pointer is within the borders of the console window and the window has the keyboard focus, mouse events generated by mouse movement and button presses are placed in the input buffer. These events are discarded by ReadFile or ReadConsole, even when this mode is enabled.

If the hConsoleHandle parameter is a screen buffer handle, the mode can be a combination of the following values. When a screen buffer is created, both output modes are enabled by default.
Value | Meaning
ENABLE_PROCESSED_OUTPUT | Characters written by the WriteFile or WriteConsole function or echoed by the ReadFile or ReadConsole function are examined for ASCII control sequences and the correct action is performed. Backspace, tab, bell, carriage return, and linefeed characters are processed.
ENABLE_WRAP_AT_EOL_OUTPUT When writing with WriteFile or WriteConsole or echoing with ReadFile or ReadConsole, the cursor moves to the beginning of the next row when it reaches the end of the current row. This causes the rows displayed in the console window to scroll up automatically when the cursor advances beyond the last row in the window. It also causes the contents of the screen buffer to scroll up (discarding the top row of the screen buffer) when the cursor advances beyond the last row in the screen buffer. If this mode is disabled, the last character in the row is overwritten with any subsequent characters.

Windows 95/98: Even if this value is specified, this EOL wrap mode does not work in Windows 95 and Windows 98.

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

A console consists of an input buffer and one or more screen buffers. The mode of a console buffer determines how the console behaves during input and output (I/O) operations. One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles. Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.

The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes that use ReadFile or ReadConsole to read from the console's input buffer. Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects ReadFile and ReadConsole users, except that it also determines whether Ctrl+C input is reported in the input buffer (to be read by the ReadConsoleInput function) or is passed to a HandlerRoutine function defined by the application.

The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions involving window resizing and mouse actions are reported in the input buffer or discarded. These events can be read by ReadConsoleInput, but they are always filtered by ReadFile and ReadConsole.

The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes using ReadFile or ReadConsole and WriteFile or WriteConsole.

To determine the current mode of a console input buffer or a screen buffer, use the GetConsoleMode function.

For an example, see Reading Input Buffer Events.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleMode, HandlerRoutine, ReadConsole, ReadConsoleInput, ReadFile, WriteConsole, WriteFile


SetConsoleOutputCP

The SetConsoleOutputCP function sets the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.

BOOL SetConsoleOutputCP(
  UINT wCodePageID   // code page
);

Parameters

wCodePageID
[in] Specifies the identifier of the code page to set. The identifiers of the code pages available on the local computer are stored in the registry under the following key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage

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

A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages.

To determine a console's current output code page, use the GetConsoleOutputCP function. To set and retrieve a console's input code page, use the SetConsoleCP and GetConsoleCP functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleCP, GetConsoleOutputCP, SetConsoleCP


SetConsoleScreenBufferSize

The SetConsoleScreenBufferSize function changes the size of the specified console screen buffer.

BOOL SetConsoleScreenBufferSize(
  HANDLE hConsoleOutput,  // handle to screen buffer
  COORD dwSize            // new screen buffer size
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
dwSize
[in] Specifies a COORD structure containing the new size, in rows and columns, of the screen buffer. The specified width and height cannot be less than the width and height of the screen buffer's window. The specified dimensions also cannot be less than the minimum size allowed by the system. This minimum depends on the current font size for the console (selected by the user) and the SM_CXMIN and SM_CYMIN values returned by the GetSystemMetrics function.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, COORD, GetConsoleScreenBufferInfo, SetConsoleWindowInfo


SetConsoleTextAttribute

The SetConsoleTextAttribute function sets the foreground (text) and background color attributes of characters written to the screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects only text written after the function call.

BOOL SetConsoleTextAttribute(
  HANDLE hConsoleOutput,  // handle to screen buffer
  WORD wAttributes        // text and background colors
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_READ access.
wAttributes
[in] Specifies the foreground and background color attributes. Any combination of the following values can be specified: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces white text on a black background:
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE

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

To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function.

For an example, see Using the High-Level Input and Output Functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleScreenBufferInfo, ReadConsole, ReadFile, WriteConsole, WriteFile


SetConsoleTitle

The SetConsoleTitle function sets the title bar string for the current console window.

BOOL SetConsoleTitle(
  LPCTSTR lpConsoleTitle   // new console title
);

Parameters

lpConsoleTitle
[in] Pointer to a null-terminated string that contains the string to appear in the title bar of the console window.

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

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleTitle, SetConsoleCP, SetConsoleOutputCP


SetConsoleWindowInfo

The SetConsoleWindowInfo function sets the current size and position of a console screen buffer's window.

BOOL SetConsoleWindowInfo(
  HANDLE hConsoleOutput,            // handle to screen buffer
  BOOL bAbsolute,                   // coordinate type
  CONST SMALL_RECT *lpConsoleWindow // window corners
);

Parameters

hConsoleOutput
[in] Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
bAbsolute
[in] Specifies how the coordinates in the structure pointed to by the lpConsoleWindow parameter are used. If bAbsolute is TRUE, the coordinates specify the new upper-left and lower-right corners of the window. If it is FALSE, the coordinates are offsets to the current window-corner coordinates.
lpConsoleWindow
[in] Pointer to a SMALL_RECT structure that contains values that determine the new upper-left and lower-right corners of the window.

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

The function fails if the specified window rectangle extends beyond the boundaries of the screen buffer. This means that the Top and Left members of the lpConsoleWindow rectangle (or the calculated top and left coordinates, if bAbsolute is FALSE) cannot be less than zero. Similarly, the Bottom and Right members (or the calculated bottom and right coordinates) cannot be greater than (screen buffer height – 1) and (screen buffer width – 1), respectively. The function also fails if the Right member (or calculated right coordinate) is less than or equal to the Left member (or calculated left coordinate) or if the Bottom member (or calculated bottom coordinate) is less than or equal to the Top member (or calculated top coordinate).

For consoles with more than one screen buffer, changing the window location for one screen buffer does not affect the window locations of the other screen buffers.

To determine the current size and position of a screen buffer's window, use the GetConsoleScreenBufferInfo function. This function also returns the maximum size of the window, given the current screen buffer size, the current font size, and the screen size. The GetLargestConsoleWindowSize function returns the maximum window size given the current font and screen sizes, but it does not consider the size of the screen buffer.

SetConsoleWindowInfo can be used to scroll the contents of the screen buffer by shifting the position of the window rectangle without changing its size.

For an example, see Scrolling a Screen Buffer's Window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleScreenBufferInfo, GetLargestConsoleWindowSize, SMALL_RECT, ScrollConsoleScreenBuffer


SetStdHandle

The SetStdHandle function sets the handle for the standard input, standard output, or standard error device.

BOOL SetStdHandle(
  DWORD nStdHandle,  // input, output, or error device
  HANDLE hHandle     // handle
);

Parameters

nStdHandle
[in] Specifies the standard handle to be set. This parameter can be one of the following values.
Value | Meaning
STD_INPUT_HANDLE | Standard input handle
STD_OUTPUT_HANDLE | Standard output handle
STD_ERROR_HANDLE | Standard error handle

hHandle
[in] Handle to set as standard input, standard output, or standard error.

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

The standard handles of a process may have been redirected by a call to SetStdHandle, in which case GetStdHandle will return the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle to a console's input buffer. Similarly, you can specify the CONOUT$ value to get a handle to the console's active screen buffer.

For an example, see Creating a Child Process with Redirected Input and Output.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CreateFile, GetStdHandle


WriteConsole

The WriteConsole function writes a character string to a console screen buffer beginning at the current cursor location.

BOOL WriteConsole(
  HANDLE hConsoleOutput,           // handle to screen buffer
  CONST VOID *lpBuffer,            // write buffer
  DWORD nNumberOfCharsToWrite,     // number of characters to write
  LPDWORD lpNumberOfCharsWritten,  // number of characters written
  LPVOID lpReserved                // reserved
);

Parameters

hConsoleOutput
[in] Handle to the console screen buffer to be written to. The handle must have GENERIC_WRITE access.
lpBuffer
[in] Pointer to a buffer that contains characters to be written to the screen buffer.
nNumberOfCharsToWrite
[in] Specifies the number of characters to write.
lpNumberOfCharsWritten
[out] Pointer to a variable that receives the number of TCHARs actually written. For the ANSI version of this function, this is the number of bytes; for the Unicode version, this is the number of characters.
lpReserved
Reserved; must be NULL.

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

WriteConsole writes characters to a console screen buffer. It behaves like the WriteFile function, except it can write in either Unicode or ANSI mode. To create an application that maintains a single set of sources compatible with both modes, use WriteConsole rather than WriteFile. Although WriteConsole can be used only with a console screen buffer handle, WriteFile can be used with other handles (such as files or pipes). WriteConsole fails if used with a standard handle that has been redirected to be something other than a console handle.

Although an application can use WriteConsole in ANSI mode to write ANSI characters, consoles do not support ANSI escape sequences. However, some functions provide equivalent functionality: for example, SetCursorPos, SetConsoleTextAttribute, and GetConsoleCursorInfo.

WriteConsole writes characters to the screen buffer at the current cursor position. The cursor position advances as characters are written. The SetConsoleCursorPosition function sets the current cursor position.

Characters are written using the foreground and background color attributes associated with the screen buffer. The SetConsoleTextAttribute function changes these colors. To determine the current color attributes and the current cursor position, use GetConsoleScreenBufferInfo.

All of the input modes that affect the behavior of WriteFile have the same effect on WriteConsole. To retrieve and set the output modes of a console screen buffer, use the GetConsoleMode and SetConsoleMode functions.

Windows NT/2000 or later: This function uses either Unicode characters or ANSI characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, GetConsoleCursorInfo, GetConsoleMode, GetConsoleScreenBufferInfo, ReadConsole, SetConsoleCP, SetConsoleCursorPosition, SetConsoleMode, SetConsoleOutputCP, SetConsoleTextAttribute, SetCursorPos, WriteFile


WriteConsoleInput

The WriteConsoleInput function writes data directly to the console input buffer.

BOOL WriteConsoleInput(
  HANDLE hConsoleInput,           // handle to console input buffer
  CONST INPUT_RECORD *lpBuffer,   // data buffer
  DWORD nLength,                  // number of records to write
  LPDWORD lpNumberOfEventsWritten // number of records written
);

Parameters

hConsoleInput
[in] Handle to the console input buffer. The handle must have GENERIC_WRITE access.
lpBuffer
[in] Pointer to an INPUT_RECORD buffer containing data to be written to the input buffer.
nLength
[in] Specifies the number of input records to be written.
lpNumberOfEventsWritten
[out] Pointer to a variable that receives the number of input records actually written.

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

WriteConsoleInput places input records into the input buffer behind any pending events in the buffer. The input buffer grows dynamically, if necessary, to hold as many events as are written.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, INPUT_RECORD, PeekConsoleInput, ReadConsoleInput, SetConsoleCP, SetConsoleOutputCP


WriteConsoleOutput

The WriteConsoleOutput function writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer. The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer.

BOOL WriteConsoleOutput(
  HANDLE hConsoleOutput,      // handle to screen buffer
  CONST CHAR_INFO *lpBuffer,  // data buffer
  COORD dwBufferSize,         // size of data buffer
  COORD dwBufferCoord,        // cell coordinates
  PSMALL_RECT lpWriteRegion   // rectangle to write
);

Parameters

hConsoleOutput
[in] Handle to the screen buffer. The handle must have GENERIC_WRITE access.
lpBuffer
[in] Pointer to a source buffer that contains the data to be written to the screen buffer. This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures whose size is specified by the dwBufferSize parameter.
dwBufferSize
[in] Specifies the size, in character cells, of the buffer pointed to by the lpBuffer parameter. The X member of the COORD structure is the number of columns; the Y member is the number of rows.
dwBufferCoord
[in] Specifies the coordinates of the upper-left cell in the buffer pointed to by the lpBuffer parameter to write data from. The X member of the COORD structure is the column, and the Y member is the row.
lpWriteRegion
[in/out] Pointer to a SMALL_RECT structure. On input, the structure members specify the upper-left and lower-right coordinates of the screen buffer rectangle to write to. On output, the structure members specify the actual rectangle that was written to.

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

WriteConsoleOutput treats the source buffer and the destination screen buffer as two-dimensional arrays (columns and rows of character cells). The rectangle pointed to by the lpWriteRegion parameter specifies the size and location of the block to be written to in the screen buffer. A rectangle of the same size is located with its upper-left cell at the coordinates of the dwBufferCoord parameter in the lpBuffer array. Data from the cells that are in the intersection of this rectangle and the source buffer rectangle (whose dimensions are specified by the dwBufferSize parameter) is written to the destination rectangle.

Cells in the destination rectangle whose corresponding source location are outside the boundaries of the source buffer rectangle are left unaffected by the write operation. In other words, these are the cells for which no data is available to be written.

Before WriteConsoleOutput returns, it sets the members of lpWriteRegion to the actual screen buffer rectangle affected by the write operation. This rectangle reflects the cells in the destination rectangle for which there existed a corresponding cell in the source buffer, because WriteConsoleOutput clips the dimensions of the destination rectangle to the boundaries of the screen buffer.

If the rectangle specified by lpWriteRegion lies completely outside the boundaries of the screen buffer, or if the corresponding rectangle is positioned completely outside the boundaries of the source buffer, no data is written. In this case, the function returns with the members of the structure pointed to by the lpWriteRegion parameter set such that the Right member is less than the Left, or the Bottom member is less than the Top. To determine the size of the screen buffer, use the GetConsoleScreenBufferInfo function.

WriteConsoleOutput has no effect on the cursor position.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Reading and Writing Blocks of Characters and Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, CHAR_INFO, COORD, GetConsoleScreenBufferInfo, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, SetConsoleCP, SetConsoleOutputCP, SMALL_RECT, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter


WriteConsoleOutputAttribute

The WriteConsoleOutputAttribute function copies a number of foreground and background color attributes to consecutive cells of a console screen buffer, beginning at a specified location.

BOOL WriteConsoleOutputAttribute(
  HANDLE hConsoleOutput,         // handle to screen buffer
  CONST WORD *lpAttribute,       // write attributes
  DWORD nLength,                 // number of cells
  COORD dwWriteCoord,            // first cell coordinates
  LPDWORD lpNumberOfAttrsWritten // number of cells written
);

Parameters

hConsoleOutput
[in] Handle to the screen buffer. The handle must have GENERIC_WRITE access.
lpAttribute
[in] Pointer to a buffer that contains the attributes to write to the screen buffer.
nLength
[in] Specifies the number of screen buffer character cells to write to.
dwWriteCoord
[in] Specifies the column and row coordinates of the first cell in the screen buffer to write to.
lpNumberOfAttrsWritten
[out] Pointer to a variable that receives the number of attributes actually written to the screen buffer.

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

If the number of attributes to be written to extends beyond the end of the specified row in the screen buffer, attributes are written to the next row. If the number of attributes to be written to extends beyond the end of the screen buffer, the attributes are written up to the end of the screen buffer.

The character values at the positions written to are not changed.

Each attribute specifies the foreground (text) and background colors in which that character cell is drawn. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:

FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE

For an example, see Writing Characters or Colors to Consecutive Cells.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, WriteConsoleOutput, WriteConsoleOutputCharacter


WriteConsoleOutputCharacter

The WriteConsoleOutputCharacter function copies a number of characters to consecutive cells of a console screen buffer, beginning at a specified location.

BOOL WriteConsoleOutputCharacter(
  HANDLE hConsoleOutput,          // handle to screen buffer
  LPCTSTR lpCharacter,            // characters
  DWORD nLength,                  // number of characters to write
  COORD dwWriteCoord,             // first cell coordinates
  LPDWORD lpNumberOfCharsWritten  // number of cells written
);

Parameters

hConsoleOutput
[in] Handle to the screen buffer. The handle must have GENERIC_WRITE access.
lpCharacter
[in] Pointer to a buffer that contains the characters to write to the screen buffer.
nLength
[in] Specifies the number of TCHARs to write. For the ANSI version of the function, this is the number of bytes; for the Unicode version, this is the number of characters.
dwWriteCoord
[in] Specifies the column and row coordinates of the first cell in the screen buffer to write to.
lpNumberOfCharsWritten
[out] Pointer to a variable that receives the number of TCHARs actually written. For the ANSI version of the function, this is the number of bytes; for the Unicode version, this is the number of characters.

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

If the number of characters to be written to extends beyond the end of the specified row in the screen buffer, characters are written to the next row. If the number of characters to be written to extends beyond the end of the screen buffer, characters are written up to the end of the screen buffer.

The attribute values at the positions written to are not changed.

Windows NT/2000 or later: This function uses either Unicode characters or 8-bit characters from the console's current code page. The console's code page defaults initially to the system's OEM code page. To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions, or use the chcp or mode con cp select= commands.

For an example, see Writing Characters or Colors to Consecutive Cells.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Consoles and Character-Mode Support Overview, Console Functions, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, SetConsoleCP, SetConsoleOutputCP, WriteConsoleOutput, WriteConsoleOutputAttribute


Console Structures

The following structures are used to access a console.

CHAR_INFO
CONSOLE_CURSOR_INFO
CONSOLE_SCREEN_BUFFER_INFO
COORD
FOCUS_EVENT_RECORD
INPUT_RECORD
KEY_EVENT_RECORD
MENU_EVENT_RECORD
MOUSE_EVENT_RECORD
SMALL_RECT
WINDOW_BUFFER_SIZE_RECORD


CHAR_INFO

The CHAR_INFO structure specifies the Unicode or ANSI character and the foreground (text) and background color attributes of a screen buffer character cell. This structure is used by console functions to read from and write to a console screen buffer.

typedef struct _CHAR_INFO {
  // Unicode or ANSI character
  union {
      WCHAR UnicodeChar;
      CHAR AsciiChar;
  } Char;

  // Text and background colors
  WORD Attributes;
} CHAR_INFO, *PCHAR_INFO;

Members

Char
Specifies either the Unicode (wide-character) or ANSI character of a screen buffer character cell, depending on whether the Unicode or ANSI version of the function is used.
Attributes
Specifies the foreground (text) and background colors in which a screen buffer character cell is drawn. This member can be zero, or it can be any combination of the following values:

BACKGROUND_BLUE
FOREGROUND_BLUE
BACKGROUND_GREEN
FOREGROUND_GREEN
BACKGROUND_RED
FOREGROUND_RED
BACKGROUND_INTENSITY
FOREGROUND_INTENSITY

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, ReadConsoleOutput, ScrollConsoleScreenBuffer, WriteConsoleOutput


CONSOLE_CURSOR_INFO

The CONSOLE_CURSOR_INFO structure contains information about the console cursor.

typedef struct _CONSOLE_CURSOR_INFO {
  DWORD  dwSize;
  BOOL   bVisible;
} CONSOLE_CURSOR_INFO, *PCONSOLE_CURSOR_INFO;

Members

dwSize
Specifies a number between 1 and 100, indicating the percentage of the character cell that is filled by the cursor. The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal line at the bottom of the cell.
bVisible
Specifies the visibility of the cursor. If the cursor is visible, this member is TRUE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, GetConsoleCursorInfo, SetConsoleCursorInfo


CONSOLE_SCREEN_BUFFER_INFO

The CONSOLE_SCREEN_BUFFER_INFO structure contains information about a console screen buffer.

typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
  COORD      dwSize;
  COORD      dwCursorPosition;
  WORD       wAttributes;
  SMALL_RECT srWindow;
  COORD      dwMaximumWindowSize;
} CONSOLE_SCREEN_BUFFER_INFO ;

Members

dwSize
Specifies the size, in character columns and rows, of the screen buffer.
dwCursorPosition
Specifies the column and row coordinates of the cursor in the screen buffer.
wAttributes
Specifies the foreground (text) and background color attributes to be used for characters that are written to a screen buffer by the WriteFile and WriteConsole functions, or echoed to a screen buffer by the ReadFile and ReadConsole functions. The attribute values are some combination of the following values: FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_RED, FOREGROUND_INTENSITY, BACKGROUND_BLUE, BACKGROUND_GREEN, BACKGROUND_RED, and BACKGROUND_INTENSITY. For example, the following combination of values produces red text on a white background:
FOREGROUND_RED | BACKGROUND_RED | BACKGROUND_GREEN |
BACKGROUND_BLUE
srWindow
Specifies a SMALL_RECT structure that contains the screen buffer coordinates of the upper-left and lower-right corners of the display window.
dwMaximumWindowSize
Specifies the maximum size of the console window, given the current screen buffer size and font and the screen size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, GetConsoleScreenBufferInfo, ReadConsole, ReadFile, SMALL_RECT, WriteConsole, WriteFile


COORD

The COORD structure defines the coordinates of a character cell in a console screen buffer. The origin of the coordinate system (0,0) is at the top, left cell of the buffer.

typedef struct _COORD {
  SHORT X;
  SHORT Y;
} COORD;

Members

X
Horizontal coordinate or column value.
Y
Vertical coordinate or row value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures


FOCUS_EVENT_RECORD

The FOCUS_EVENT_RECORD structure is used to report focus events in a console INPUT_RECORD structure. These events are used internally and should be ignored.

typedef struct _FOCUS_EVENT_RECORD {
  BOOL bSetFocus;
} FOCUS_EVENT_RECORD;

Members

bSetFocus
Reserved.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, INPUT_RECORD


INPUT_RECORD

The INPUT_RECORD structure is used to report input events in the console input buffer. These records can be read from the input buffer by using the ReadConsoleInput or PeekConsoleInput function, or written to the input buffer by using the WriteConsoleInput function.

typedef struct _INPUT_RECORD {
  WORD EventType;
  union {
      KEY_EVENT_RECORD KeyEvent;
      MOUSE_EVENT_RECORD MouseEvent;
      WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
      MENU_EVENT_RECORD MenuEvent;
      FOCUS_EVENT_RECORD FocusEvent;
  } Event;
} INPUT_RECORD;

Members

EventType
Handle to the type of input event and the event record stored in the Event member.

This member can have one of the following values:
Value | Meaning
KEY_EVENT | The Event member contains a KEY_EVENT_RECORD structure with information about a keyboard event.
MOUSE_EVENT | The Event member contains a MOUSE_EVENT_RECORD structure with information about a mouse movement or button press event.
WINDOW_BUFFER_SIZE_EVENT | The Event member contains a WINDOW_BUFFER_SIZE_RECORD structure with information about the new size of the screen buffer.
MENU_EVENT | The Event member contains a MENU_EVENT_RECORD structure. These events are used internally and should be ignored.
FOCUS_EVENT | The Event member contains a FOCUS_EVENT_RECORD structure. These events are used internally and should be ignored.

Event
Contains a KEY_EVENT_RECORD, MOUSE_EVENT_RECORD, WINDOW_BUFFER_SIZE_RECORD, MENU_EVENT_RECORD, or FOCUS_EVENT_RECORD structure, depending on the event type specified by the EventType member.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, FOCUS_EVENT_RECORD, KEY_EVENT_RECORD, MENU_EVENT_RECORD, MOUSE_EVENT_RECORD, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


KEY_EVENT_RECORD

The KEY_EVENT_RECORD structure is used to report keyboard input events in a console INPUT_RECORD structure.

typedef struct _KEY_EVENT_RECORD {
  BOOL bKeyDown;
  WORD wRepeatCount;
  WORD wVirtualKeyCode;
  WORD wVirtualScanCode;
  union {
      WCHAR UnicodeChar;
      CHAR  AsciiChar;
  } uChar;
  DWORD dwControlKeyState;
} KEY_EVENT_RECORD;

Members

bKeyDown
Specifies TRUE if the key is being pressed, FALSE if the key is being released.
wRepeatCount
Specifies a count indicating that a key is being held down. For example, when a key is held down, you might get five events with this member equal to 1, one event with this member equal to 5, or multiple events with this member greater than or equal to 1.
wVirtualKeyCode
Specifies the virtual-key code that identifies the given key in a device-independent manner.
wVirtualScanCode
Specifies the virtual scan code of the given key that represents the device-dependent value generated by the keyboard hardware.
uChar
Specifies the translated Unicode or ASCII character, depending on whether the wide-character (Unicode) or ANSI version of the ReadConsoleInput function was used.
dwControlKeyState
Indicates the state of the control keys. This member can be one or more of the following values.
Value | Meaning
CAPSLOCK_ON | The CAPS LOCK light is on.
ENHANCED_KEY | The key is enhanced.
LEFT_ALT_PRESSED | The left ALT key is pressed.
LEFT_CTRL_PRESSED | The left CTRL key is pressed.
NUMLOCK_ON | The NUM LOCK light is on.
RIGHT_ALT_PRESSED | The right ALT key is pressed.
RIGHT_CTRL_PRESSED | The right CTRL key is pressed.
SCROLLLOCK_ON | The SCROLL LOCK light is on.
SHIFT_PRESSED | The SHIFT key is pressed.

Remarks

Enhanced keys for the IBM® 101- and 102-key keyboards are the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and direction keys in the clusters to the left of the keypad; and the divide (/) and ENTER keys in the keypad.

Keyboard input events are generated when any key, including control keys, is pressed or released. However, the ALT key when pressed and released without combining with another character, has special meaning to the system and is not passed through to the application. Also, the CTRL+C key combination is not passed through if the input handle is in processed mode (ENABLE_PROCESSED_INPUT).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput, INPUT_RECORD


MENU_EVENT_RECORD

The MENU_EVENT_RECORD structure reports menu events in a console INPUT_RECORD structure. These events are used internally and should be ignored.

typedef struct _MENU_EVENT_RECORD {
  UINT dwCommandId;
} MENU_EVENT_RECORD, *PMENU_EVENT_RECORD;

Members

dwCommandId
Reserved.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, INPUT_RECORD


MOUSE_EVENT_RECORD

The MOUSE_EVENT_RECORD structure is used in a console INPUT_RECORD structure to report mouse input events.

typedef struct _MOUSE_EVENT_RECORD {
  COORD dwMousePosition;
  DWORD dwButtonState;
  DWORD dwControlKeyState;
  DWORD dwEventFlags;
} MOUSE_EVENT_RECORD;

Members

dwMousePosition
Specifies the location of the cursor in terms of the screen buffer's character-cell coordinates.
dwButtonState
Indicates the status of the mouse buttons. The least significant bit corresponds to the leftmost mouse button. The next least significant bit corresponds to the rightmost mouse button. The next bit indicates the next-to-leftmost mouse button. The bits then correspond left to right to the mouse buttons. A bit is 1 if the button was pressed.

The following constants are defined for the first five mouse buttons:

FROM_LEFT_1ST_BUTTON_PRESSED
RIGHTMOST_BUTTON_PRESSED
FROM_LEFT_2ND_BUTTON_PRESSED
FROM_LEFT_3RD_BUTTON_PRESSED
FROM_LEFT_4TH_BUTTON_PRESSED

dwControlKeyState
Indicates the state of the control keys. This member can be one or more of the following values.
Value | Meaning
RIGHT_ALT_PRESSED | The right ALT key is pressed.
LEFT_ALT_PRESSED | The left ALT key is pressed.
RIGHT_CTRL_PRESSED | The right CTRL key is pressed.
LEFT_CTRL_PRESSED | The left CTRL key is pressed.
CAPSLOCK_ON | The CAPS LOCK light is on.
ENHANCED_KEY | The key is enhanced.
NUMLOCK_ON | The NUM LOCK light is on.
SCROLLLOCK_ON | The SCROLL LOCK light is on.
SHIFT_PRESSED | The SHIFT key is pressed.

dwEventFlags
Indicates the type of mouse event. If this value is zero, it indicates a mouse button being pressed or released. Otherwise, this member is one of the following values.
Value | Meaning
DOUBLE_CLICK | The second click (button press) of a double-click occurred. The first click is returned as a regular button-press event.
MOUSE_MOVED | A change in mouse position occurred.
MOUSE_WHEELED | Windows 2000 or later: The mouse wheel was rolled.

Remarks

Mouse events are placed in the input buffer when the console is in mouse mode (ENABLE_MOUSE_INPUT).

Mouse events are generated whenever the user moves the mouse, or presses or releases one of the mouse buttons. Mouse events are placed in a console's input buffer only when the console group has the keyboard focus and the cursor is within the borders of the console's window.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, INPUT_RECORD, PeekConsoleInput, ReadConsoleInput, WriteConsoleInput


SMALL_RECT

The SMALL_RECT structure defines the coordinates of the upper left and lower right corners of a rectangle.

typedef struct _SMALL_RECT {
  SHORT Left;
  SHORT Top;
  SHORT Right;
  SHORT Bottom;
} SMALL_RECT;

Members

Left
Specifies the x-coordinate of the upper left corner of the rectangle.
Top
Specifies the y-coordinate of the upper left corner of the rectangle.
Right
Specifies the x-coordinate of the lower right corner of the rectangle.
Bottom
Specifies the y-coordinate of the lower right corner of the rectangle.

Remarks

This structure is used by console functions to specify rectangular areas of console screen buffers, where the coordinates specify the rows and columns of screen-buffer character cells.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, RECT, RECTL


WINDOW_BUFFER_SIZE_RECORD

The WINDOW_BUFFER_SIZE_RECORD structure is used in a console INPUT_RECORD structure to report changes in the size of the screen buffer.

typedef struct _WINDOW_BUFFER_SIZE_RECORD {
  COORD dwSize;
} WINDOW_BUFFER_SIZE_RECORD;

Members

dwSize
Specifies the new size of the screen buffer, in character cell columns and rows.

Remarks

Buffer size events are placed in the input buffer when the console is in window-aware mode (ENABLE_WINDOW_INPUT).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Wincon.h; include Windows.h.

See Also

Consoles and Character-Mode Support Overview, Console Structures, INPUT_RECORD, ReadConsoleInput


Data Decompression Library

This overview describes concepts relating to data compression and describes the decompression functions.

  • About the Data Decompression Library
  • Using the Data Decompression Library
  • Data Decompression Library Reference


About the Data Decompression Library

Typically, an application calls functions in LzExpand.dll to decompress data previously compressed by using the Microsoft® File Compression Utility (Compress.exe).

  • Data Compression
  • Data Decompression


Data Compression

Data compression reduces the size of a file by minimizing redundant data. In a text file, redundant data can be frequently occurring characters, such as the space character, or common vowels, such as the letters e and a; it can also be frequently occurring character strings. Data compression creates a compressed version of a file by minimizing this redundant data.

Each type of data-compression algorithm minimizes redundant data in a unique manner. For example, the Huffman encoding algorithm assigns a code to characters in a file based on how frequently those characters occur. Another compression algorithm, called run-length encoding, generates a two-part value for repeated characters: the first part specifies the number of times the character is repeated, and the second part identifies the character. Another compression algorithm, known as the Lempel-Ziv algorithm, converts variable-length strings into fixed-length codes that consume less space than the original strings.

To compress large applications or data files, run Compress.exe from the command line. Compress.exe uses the Lempel-Ziv compression algorithm.


Data Decompression

Applications can call the functions in LzExpand.dll to decompress files compressed by using Compress.exe. The functions can also process uncompressed files without attempting to decompress them.

The following table describes each function found in LzExpand.dll.

Function | Purpose
GetExpandedName | Retrieves the original name of a compressed file, if the /r option was used during compression of the file.
LZClose | Closes a file that was opened when the application called the LZOpenFile function.
LZCopy | Copies a source file to a destination file. If the source file is compressed, this function creates a decompressed destination file. If the source file is not compressed, this function duplicates the original file. This function is intended for single-file copy operations.
LZInit | Creates structures used for decompressing files.
LZOpenFile | Opens a file and returns a handle that identifies it.
LZRead | Reads a specified number of bytes from a file. If the file is compressed, this function decompresses the bytes before copying them to the destination buffer.
LZSeek | Positions the file pointer within the decompressed image of a compressed file. The application calls this function to position the pointer before calling the LZRead function.


Using the Data Decompression Library

You can use the functions in LzExpand.dll to decompress single or multiple files. You can also use them to decompress compressed files a portion at a time.

  • Decompressing a single file
  • Decompressing multiple files
  • Reading bytes from compressed files


Decompressing a Single File

An application can decompress a single compressed file by performing the following tasks.

  1. Open the source file by calling the LZOpenFile function.
  2. Open the destination file by calling LZOpenFile.
  3. Copy the source file to the destination file by calling the LZCopy function and passing the handles returned by LZOpenFile.
  4. Close the files by calling the LZClose function.


Decompressing Multiple Files

An application can decompress multiple files by performing the following tasks.

  1. Open the source files by calling the LZOpenFile function.
  2. Open the destination files by calling LZOpenFile.
  3. Copy the source files to the destination files by calling the LZCopy function.
  4. Close the files by calling the LZClose function.


Reading Bytes from Compressed Files

In addition to decompressing a complete file in a single operation, an application can decompress a compressed file a portion at a time by using the LZSeek and LZRead functions. These functions are particularly useful when it is necessary to extract parts of large files. For example, a font manufacturer may have compressed files containing font metrics in addition to character data. To use the information in these files, an application would need to decompress the file; however, most applications would use only part of the file at any particular time. To get information about font metrics, the application would extract data from the header. To get information from the text, the application would reposition the file pointer by calling LZSeek and extract character data by calling LZRead.


Data Decompression Library Reference

The following elements are used to decompress files.

  • Data Decompression Library Functions


Data Decompression Library Functions

The following functions are used to decompress files.

Function | Description
GetExpandedName | Retrieves the original name of a compressed file.
LZClose | Closes a file that was opened by using LZOpenFile.
LZCopy | Copies a source file to a destination file. If the source file is compressed with the Microsoft File Compression Utility (Compress.exe), this function creates a decompressed destination file.
LZInit | Allocates memory for the internal data structures required to decompress files, and then creates and initializes them.
LZOpenFile | Creates, opens, reopens, or deletes the specified file.
LZRead | Reads (at most) the specified number of bytes from a file and copies them into a buffer.
LZSeek | Moves a file pointer a number of bytes from a starting position.


GetExpandedName

The GetExpandedName function retrieves the original name of a compressed file, if the file was compressed by using the Microsoft File Compression Utility (Compress.exe) and the /r option was specified.

INT GetExpandedName(
  LPTSTR lpszSource,  // name of compressed file
  LPTSTR lpszBuffer   // original file name
);

Parameters

lpszSource
[in] Pointer to a string that specifies the name of a compressed file.
lpszBuffer
[out] Pointer to a buffer that receives the name of the compressed file.

Return Values

If the function succeeds, the return value is 1.

If the function fails, the return value is LZERROR_BADVALUE. There is no extended error information for this function; do not call GetLastError.

Note GetExpandedName calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

Remarks

The contents of the buffer pointed to by the lpszBuffer parameter is the original file name if the file was compressed by using the /r option. If the /r option was not used, this function duplicates the name in the lpszSource parameter into the lpszBuffer buffer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Data Decompression Library Overview, Data Decompression Library Functions


LZClose

The LZClose function closes a file that was opened by using the LZOpenFile function.

VOID LZClose(
  INT hFile   // LZ file handle
);

Parameters

hFile
[in] Handle to the source file to be closed.

Return Values

This function does not return a value.

Remarks

The handle identifying the file must be retrieved by calling the LZOpenFile function. If the handle is retrieved by calling the CreateFile or OpenFile function, an error occurs.

If the file is compressed by using the Microsoft File Compression Utility (Compress.exe) and opened by using LZOpenFile, LZClose frees any global heap space that was allocated to expand the file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.

See Also

Data Decompression Library Overview, Data Decompression Library Functions, CreateFile, LZOpenFile, OpenFile


LZCopy

The LZCopy function copies a source file to a destination file. If the source file is compressed with the Microsoft File Compression Utility (Compress.exe), this function creates a decompressed destination file. If the source file is not compressed, this function duplicates the original file.

LONG LZCopy(
  INT hfSource,  // LZ file handle for source file
  INT hfDest     // LZ file handle for destination file
);

Parameters

hfSource
[in] Handle to the source file.
hfDest
[in] Handle to the destination file.

Return Values

If the function succeeds, the return value specifies the size, in bytes, of the destination file.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZCopy calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

The following is a list of error codes that LZCopy can return upon failure.

Value | Meaning
LZERROR_BADINHANDLE | The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADOUTHANDLE | The handle identifying the destination file is not valid. The file cannot be written.
LZERROR_GLOBALLOC | The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK | The LZ file handle cannot be locked down.
LZERROR_READ | The source file format is not valid.

There is no extended error information for this function; do not call GetLastError.

Remarks

The handles identifying the source and destination files must be retrieved by calling the LZInit or LZOpenFile function.

If the function succeeds, the file identified by the hfDest parameter is always uncompressed.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.

See Also

Data Decompression Library Overview, Data Decompression Library Functions, LZInit, LZOpenFile


LZInit

The LZInit function allocates memory for the internal data structures required to decompress files, and then creates and initializes them.

INT LZInit(
  INT hfSource   // handle to source file
);

Parameters

hfSource
[in] Handle to the source file.

Return Values

If the function succeeds, the return value is a new LZ file handle.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZInit calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

The following is the list of the error codes that LZInit can return upon failure.

Value | Meaning
LZERROR_BADINHANDLE | The handle identifying the source file is not valid. The file cannot be read.
LZERROR_GLOBALLOC | The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK | The LZ file handle cannot be locked down.
LZERROR_UNKNOWNALG | The file is compressed with an unrecognized compression algorithm.

There is no extended error information for this function; do not call GetLastError.

Remarks

A maximum of 16 compressed files can be open at any given time. Similarly, a maximum of 16 uncompressed files can be open at any given time. An application should be careful to close the handle returned by LZInit when it is done using the file; otherwise, the application can inadvertently hit the 16-file limit.

The handle this function returns is compatible only with the functions in LzExpand.dll; it should not be used for other file operations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.

See Also

Data Decompression Library Overview, Data Decompression Library Functions


LZOpenFile

The LZOpenFile function creates, opens, reopens, or deletes the specified file.

INT LZOpenFile(
  LPTSTR lpFileName,       // file name
  LPOFSTRUCT lpReOpenBuf,  // file information buffer
  WORD wStyle              // action to take
);

Parameters

lpFileName
[in] Pointer to a string that specifies the name of a file.
lpReOpenBuf
[out] Pointer to the OFSTRUCT structure that is to receive information about the file when the file is first opened. The structure can be used in subsequent calls to the LZOpenFile function to refer to the open file.

The szPathName member of this structure contains characters from the original equipment manufacturer (OEM) character set.

wStyle
[in] Specifies the action to take. This parameter can be one or more of the following values.
Value | Meaning
OF_CANCEL | Ignored. In the Win32-based application programming interface (API), the OF_PROMPT style produces a dialog box containing a Cancel button.
OF_CREATE | Directs LZOpenFile to create a new file. If the file already exists, it is truncated to zero length.
OF_DELETE | Deletes the file.
OF_EXIST | Opens the file and then closes it to test for a file's existence.
OF_PARSE | Fills the OFSTRUCT structure but carries out no other action.
OF_PROMPT | Displays a dialog box if the requested file does not exist. The dialog box informs the user that the system cannot find the file, and it contains Retry and Cancel buttons. Clicking the Cancel button directs LZOpenFile to return a file not found error message.
OF_READ | Opens the file for reading only.
OF_READWRITE | Opens the file for reading and writing.
OF_REOPEN | Opens the file using information in the reopen buffer.
OF_SHARE_DENY_NONE | Opens the file without denying other processes read or write access to the file. LZOpenFile fails if the file has been opened in compatibility mode by any other process.
OF_SHARE_DENY_READ | Opens the file and denies other processes read access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been opened for read access by any other process.
OF_SHARE_DENY_WRITE | Opens the file and denies other processes write access to the file. LZOpenFile fails if the file has been opened in compatibility mode or has been opened for write access by any other process.
OF_SHARE_EXCLUSIVE | Opens the file in exclusive mode, denying other processes both read and write access to the file. LZOpenFile fails if the file has been opened in any other mode for read or write access, even by the current process.
OF_WRITE | Opens the file for writing only.

Return Values

If the function succeeds and the value specified by the wStyle parameter is not OF_READ, the return value is a handle identifying the file. If the file is compressed and opened with wStyle set to OF_READ, the return value is a special file handle.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. There is no extended error information for this function; do not call GetLastError.

Note LZOpenFile calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

The following is the list of the error codes that LZOpenFile can return upon failure.

Value | Meaning
LZERROR_BADINHANDLE | The handle identifying the source file is not valid. The file cannot be read.
LZERROR_GLOBALLOC | The maximum number of open compressed files has been exceeded or local memory cannot be allocated.

Remarks

If the wStyle parameter is the OF_READ flag (or OF_READ and any of the OF_SHARE_ flags) and the file is compressed, LZOpenFile calls the LZInit function, which performs the required initialization for the decompression operations.

The handle this function returns is compatible only with the functions in LzExpand.dll; it should not be used for other file operations.

Windows NT/2000 or later: If LZOpenFile is unable to open the file specified by lpFileName, it attempts to open a file with almost the same file name, except the last character is replaced with an underscore ("_"). Thus, if an attempt to open MyProgram.exe fails, LZOpenFile tries to open MyProgram.ex_. Installation packages often substitute the underscore for the last letter of a file name extension to indicate that the file is compressed. For example, MyProgram.exe compressed might be named MyProgram.ex_. To determine the name of the file opened (if any), examine the szPathName member of the OFSTRUCT structure in the lpReOpenBuf parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Data Decompression Library Overview, Data Decompression Library Functions, LZClose, LZInit, LZRead, OFSTRUCT


LZRead

The LZRead function reads (at most) the specified number of bytes from a file and copies them into a buffer.

INT LZRead(
  INT hFile,       // LZ file handle to file
  LPSTR lpBuffer,  // buffer for bytes
  INT cbRead       // count of bytes
);

Parameters

hFile
[in] Handle to the source file.
lpBuffer
[in] Pointer to a buffer that receives the bytes read from the file.
cbRead
[in] Specifies the count of bytes to be read.

Return Values

If the function succeeds, the return value specifies the number of bytes read.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZRead calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

The following is the list of error codes that LZRead can return upon failure.

Value | Meaning
LZERROR_BADINHANDLE | The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADOUTHANDLE | The handle identifying the destination file is not valid. The file cannot be written.
LZERROR_BADVALUE | One of the input parameters is not valid.
LZERROR_GLOBALLOC | The maximum number of open compressed files has been exceeded or local memory cannot be allocated.
LZERROR_GLOBLOCK | The LZ file handle cannot be locked down.
LZERROR_READ | The source file format is not valid.
LZERROR_WRITE | There is insufficient space for the output file.

There is no extended error information for this function; do not call GetLastError.

Remarks

The handle identifying the file must be retrieved by calling either the LZInit or LZOpenFile function.

If the file is compressed, LZRead emulates the _lread function on an expanded image of the file and copies the bytes of data into the specified buffer.

Applications must call the LZOpenFile, LZSeek, and LZRead functions instead of the OpenFile, _llseek, and _lread functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.

See Also

Data Decompression Library Overview, Data Decompression Library Functions, LZInit, LZOpenFile, LZSeek


LZSeek

The LZSeek function moves a file pointer a number of bytes from a starting position.

LONG LZSeek(
  INT hFile,     // handle to source file
  LONG lOffset,  // number of bytes to move
  INT iOrigin    // starting position
);

Parameters

hFile
[in] Handle to the source file.
lOffset
[in] Specifies the number of bytes by which to move the file pointer.
iOrigin
[in] Specifies the starting position of the pointer. This parameter must be one of the following values.
Value | Meaning
0 | Moves the file pointer lOffset bytes from the beginning of the file.
1 | Moves the file pointer lOffset bytes from the current position.
2 | Moves the file pointer lOffset bytes from the end of the file.

Return Values

If the function succeeds, the return value specifies the offset from the beginning of the file to the new pointer position.

If the function fails, the return value is an LZERROR_* code. These codes have values less than zero. Note that LZSeek calls neither SetLastError nor SetLastErrorEx; thus, its failure does not affect a thread's last-error code.

The following is the list of error codes that LZSeek can return upon failure.

Value | Meaning
LZERROR_BADINHANDLE | The handle identifying the source file is not valid. The file cannot be read.
LZERROR_BADVALUE | One of the parameters is outside the range of acceptable values.
LZERROR_GLOBLOCK | The LZ file handle cannot be locked down.

There is no extended error information for this function; do not call GetLastError.

Remarks

The handle identified by the hFile parameter must be retrieved by calling either the LZInit or LZOpenFile function.

If the file is compressed, LZSeek emulates the _llseek function on an expanded image of the file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Lzexpand.h; include Windows.h.
Library: Use Lz32.lib.

See Also

Data Decompression Library Overview, Data Decompression Library Functions, LZInit, LZOpenFile


File I/O

A file is the basic unit of storage that enables a computer to distinguish one set of information from another. This overview describes the file input and output (I/O) operations and the information provided by the file I/O functions.

  • About File I/O
  • Using File I/O
  • File I/O Reference


About File I/O

Files are stored on storage media, such as disks or tapes, and can be organized into groups called directories. The file I/O functions enable applications to create, open, modify, and delete files. They also enable applications to obtain system information, such as what disk drives are present.

  • File System Organization
  • Accessing Files
  • File Name Conventions
  • File Operations
  • Directory Operations
  • Asynchronous Input and Output
  • I/O Completion Ports
  • Getting Information About Files
  • File and Directory Security


File System Organization

A volume is a storage device, such as a fixed disk or floppy disk, formatted to store directories and files. Each volume has a root directory. Directories and files on the volume are organized in a tree structure that starts at the root directory. Each directory entry identifies the name, attributes, location, and size of a file or subdirectory.

A large volume can be divided into more than one logical volume, also called a partition. To the user and to the operating system, each partition appears to be a separate volume.

A file system is operating system software that manages the low-level organization of files on a volume. The operating system supports one or more of the following file systems:

  • File Allocation Table (FAT)
  • NTFS File System (NTFS)

The type of file system defines the file name conventions on a volume and may also provide specific file system features, such as security, recoverability, and high I/O performance. Each volume can use a different file system.

For more information on FAT and NTFS, see File Systems.


Accessing Files

The first time a file function accesses a volume and whenever a diskette is placed in a floppy-disk drive, the operating system examines the volume to determine its file system. Thereafter, the operating system manages all I/O to that volume through the device driver supporting the file system.

The file I/O functions enable applications to access files regardless of the underlying file system. However, capabilities may vary depending on the file system and/or operating system in use. For example, the CreateFile function includes a security parameter that provides no security benefits for files not residing on an NTFS volume.

The file I/O functions that create, open, and delete files and directories identify them by their names. These functions store or search for the file or directory in the current directory on the current disk drive, unless the name explicitly specifies a path to a different directory, disk drive, or both.


File Name Conventions

Although each file system can have specific rules about the formation of individual components in a directory or file name, all file systems follow the same general conventions: a base file name and an optional extension, separated by a period. For example, the MS-DOS FAT file system supports 8 characters for the base file name and 3 characters for the extension. This is known as an 8.3 file name. The FAT file system and NTFS support file names that can be up to 255 characters long. This is known as a long file name. To get an MS-DOS file name given a long file name, use the GetShortPathName function. To get the full path of a file, use the GetFullPathName function.

Both file systems use the backslash (\) character to separate directory names and the file name when forming a path.

General rules for applications creating names for directories and files or processing names supplied by the user include the following:

  • Use any character in the current code page for a name, but do not use a path separator, a character in the range 0 through 31, or any character explicitly disallowed by the file system. A name can contain characters in the extended character set (128–255).
  • Use the backslash (\), the forward slash (/), or both to separate components in a path. No other character is acceptable as a path separator. Note that UNC names must adhere to the following format: \\server\share.
  • Use a period (.) as a directory component in a path to represent the current directory.
  • Use two consecutive periods (..) as a directory component in a path to represent the parent of the current directory.
  • Use a period (.) to separate the base file name from the extension in a directory name or file name.
  • Do not use the following characters in directory names or file names, because they are reserved:

    < > : " / \ |

  • Do not use device names, such as aux, con, lpt1, and prn, as file names or directory names.
  • Process a path as a null-terminated string. The maximum length for a path, including a trailing backslash, is given by MAX_PATH.

    The Unicode versions of several functions permit paths that exceed the MAX_PATH length if the path has the "\\?\" prefix. The "\\?\" tells the function to turn off path parsing. However, each component in the path cannot be more than MAX_PATH characters long. Use the "\\?\" prefix with paths for local storage devices and the "\\?\UNC\" prefix with paths having the Universal Naming Convention (UNC) format. The "\\?\" is ignored as part of the path. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private", and "\\?\UNC\bill_g_1\hotstuff\coolapps" is seen as "\\bill_g_1\hotstuff\coolapps".

  • Do not assume case sensitivity. Consider names such as OSCAR, Oscar, and oscar to be the same.
  • The following reserved words cannot be used as the name of a file: CON, PRN, AUX, CLOCK$, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also, reserved words followed by an extension—for example, NUL.tx7—are invalid file names.

By following the rules listed in this section, an application can create valid names for files and directories regardless of the file system in use.

Backslashes (\) are used as element dividers in paths (dividing the file name from the path to it, or directories from one another in a path). You cannot use them in file or directory names. They may be required as part of volume names (for example, "C:\").


Long File Names

The operating system stores the long file names on disk as special directory entries. When you create a long file name, the operating system creates a corresponding short 8.3 form of the name.

The operating system stores the long file names on disk in Unicode. This means that the original long file name is always preserved, even if it contains extended characters, and regardless of the code page that is active during a disk read or write operation. The case of the file name is preserved, but the file system is not case-sensitive.

The valid character set for these long file names is the NTFS character set, less one character: the colon (':') that NTFS uses for opening alternate file streams. This means that you can freely copy files between NTFS and FAT partitions without losing any file name information.


MS-DOS Device Names

MS-DOS device names are global. Once defined, an MS-DOS device name remains visible to all processes until either it is explicitly removed or the system restarts.

The DefineDosDevice and SetVolumeMountPoint functions are used to create and modify the symbolic links used to implement the MS-DOS device namespace. To obtain a list of all MS-DOS devices known to the system, use the QueryDosDevice function.


File Operations

There are a variety of functions for performing file operations. These functions are discussed in the following topics:

  • Creating and Opening Files with the CreateFile Function
  • Creating Temporary Files
  • Copying and Moving Files
  • Reading From and Writing to a File
  • Locking and Unlocking Files
  • Searching for Files
  • Monitoring Directories
  • Closing and Deleting Files


Creating and Opening Files with the CreateFile Function

The CreateFile function can create a new file or open an existing file.

When an application uses CreateFile, it must specify whether it will read from the file, write to the file, or both. The application must also specify what action to take whether or not the file exists. For example, an application can specify that CreateFile always be used to create the file. As a result, the function creates the file if it does not exist and overwrites the file if it does exist.

CreateFile also enables an application to specify whether it wants to share the file for reading, writing, both, or neither. A file that is not shared cannot be opened more than once by the first application nor by another application until the first application has closed the file.

The operating system assigns a unique identifier, called a file handle, to each file that is opened or created. An application can use the file handle in functions that read from, write to, and describe the file. It is valid until the file is closed. When an application starts, it inherits all open file handles from the process that started it, if the handles are inheritable. For more information about processes, see Processes and Threads.

For information about the standard input, standard output, and standard error file handles, see Consoles and Character-Mode Support.

An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurs, the application can use the GetLastError function to get extended error information.


Creating Temporary Files

Applications can obtain unique file names for temporary files with the GetTempFileName function. The GetTempPath function retrieves the path to the directory where temporary files are to be created.


Copying and Moving Files

Before a file can be copied, it must be closed or opened only for reading. No thread can have the file opened for writing. To copy an existing file to a new one, use the CopyFile or CopyFileEx function. Applications can specify whether CopyFile and CopyFileEx fail if the destination file already exists.

The CopyFileEx function also allows an application to specify the address of a callback function (see CopyProgressRoutine) that is called each time another portion of the file has been copied. The application can use this information to display am indicator that shows the total number of bytes copied as a percent of the total file size.

The ReplaceFile function replaces one file with another file, with the option of creating a backup copy of the original file. The function preserves attributes of the original file, such as its creation time, ACLs, and encryption attribute.

A file must also be closed before an application can move it. The MoveFile and MoveFileEx functions copy an existing file to a new location and deletes the original.

The MoveFileEx function also allows an application to specify how to move the file. The function can replace an existing file, move a file across volumes, and delay moving the file until the operating system is restarted.


Reading from and Writing to a File

Every open file has a file pointer that specifies the next byte to be read or the location to receive the next byte written. When a file is opened for the first time, the system places the file pointer at the beginning of the file. As each byte is read or written, the system advances the file pointer. An application can also move the file pointer by using the SetFilePointer function.

An application reads from and writes to a file by using the ReadFile and WriteFile functions. These functions require a handle to a file to be opened for reading and writing, respectively. ReadFile and WriteFile read and write a specified number of bytes at the location indicated by the file pointer. The data is read and written exactly as specified; the functions do not format the data.

An application can implement a scatter-gather scheme with ReadFileScatter and WriteFileGather. A scatter-gather scheme uses the operating system to deliver in one operation multiple discrete chunks of data (such as database records) from a file to separate, noncontiguous buffers in memory. A scatter-gather scheme also writes the data from noncontiguous buffers in one operation.

When the file pointer reaches the end of a file and the application attempts to read from the file, no error occurs, but no bytes are read. Therefore, reading zero bytes without an error means the application has reached the end of the file. Writing zero bytes does nothing.

An application can truncate or extend a file by using the SetEndOfFile function. This function sets the end of file to the current position of the file pointer.

When an application writes to a file, the system usually collects the data being written in an internal buffer and writes the data to the disk on a regular basis.

An application can force the operating system to write the contents of the buffer to the disk by using the FlushFileBuffers function. Alternatively, an application can specify that write operations are to bypass the internal buffer and write directly to the disk by setting a flag when the file is created or opened by using the CreateFile function.

If there is data in the internal buffer when the file is closed, the operating system does not automatically write the contents of the buffer to the disk before closing the file. If the application does not force the operating system to write the buffer to disk before closing the file, the caching algorithm determines when the buffer is written.

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


Locking and Unlocking Files

Although the system allows more than one application to open a file and write to it, applications must not write over each other's work. An application can prevent this problem by temporarily locking a region in a file. The LockFile and LockFileEx functions lock a specified range of bytes in a file. The range may extend beyond the current end of the file. Locking part of a file prevents all other processes from reading or writing anywhere in the specified area. Attempts to read from or write to a region locked by another process always fail.

The LockFileEx function allows an application to specify either a shared lock or an exclusive lock. An exclusive lock denies all other processes both read and write access to the specified region of the file. A shared lock denies all processes write access to the specified region of the file, including the process that first locks the region. This can be used to create a read-only region in a file.

The application unlocks the region by using the UnlockFile or UnlockFileEx function. An application should unlock all locked areas before closing a file.


Searching for Files

An application can search the current directory for all file names that match a given pattern by using the FindFirstFile, FindFirstFileEx, FindNextFile, and FindClose functions. The pattern must be a valid file name and can include wildcard characters.

The FindFirstFile and FindFirstFileEx functions create handles that FindNextFile uses to search for other files with the same pattern. All functions return information about the file that was found. This information includes the file name, size, attributes, and time.

The FindFirstFileEx function also allows an application to search for files based on additional search criteria. The function can limit searches to device names or directory names.

The FindClose function destroys handles created by FindFirstFile and FindFirstFileEx.

An application can search for a single file on a specific path by using the SearchPath function.


Monitoring Directories

An application can monitor the contents of a directory and its subdirectories by using the FindFirstChangeNotification, FindNextChangeNotification, and FindCloseChangeNotification functions. Waiting for a change notification is similar to having a read operation pending against a directory and, if necessary, its subdirectories. When something changes within the directory being watched, the read operation is completed. For example, an application can use these functions to update a directory listing whenever a file name within the monitored directory changes.

An application can specify a set of conditions that trigger a change notification by using the FindFirstChangeNotification function. The conditions include changes to file names, directory names, attributes, file size, time of last write, and security. This function also returns a handle that can be waited on by using the wait functions. If the wait condition is satisfied, FindNextChangeNotification can be used to provide a notification handle to wait on subsequent changes.

The FindCloseChangeNotification function closes the notification handle.

Another way to monitor directory changes is by using the ReadDirectoryChangesW function.


Closing and Deleting Files

To use operating system resources efficiently, an application should close files when they are no longer needed by using the CloseHandle function. If a file is open when an application terminates, the system closes it automatically.

The DeleteFile function can be used to delete a file. The file must, however, be closed before any attempt to delete it will succeed.


Directory Operations

When an application creates a new file, the operating system adds it to the specified directory. Each directory can have any number of files, up to the physical limit of the disk. An application can create new directories and delete existing directories by using the CreateDirectory, CreateDirectoryEx, and RemoveDirectory functions. An application cannot delete a directory unless it is empty.

The directory at the end of the active path is called the current directory; it is the directory in which the active application started, unless explicitly changed. An application can determine which directory is current by using the GetCurrentDirectory function. An application can change the current directory by using the SetCurrentDirectory function.

Windows NT/2000 or later: You can obtain a handle to a directory by calling the CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag set, as follows:

hDir = CreateFile (
    DirName,
    GENERIC_READ,
    FILE_SHARE_READ|FILE_SHARE_DELETE,
    NULL,
    OPEN_EXISTING,
    FILE_FLAG_BACKUP_SEMANTICS,
    NULL
);

You can pass a directory handle to the following functions:

BackupRead
BackupSeek
BackupWrite
GetFileInformationByHandle
GetFileSize
GetFileTime
GetFileType
ReadDirectoryChangesW
SetFileTime


Asynchronous Input and Output

Asynchronous input and output (asynchronous I/O) allows some I/O functions to return immediately, even though an I/O request is still pending. Asynchronous I/O enables an application to continue with other processing and wait for the I/O to be completed at a later time. Asynchronous I/O is also called overlapped I/O.

The ReadFile and WriteFile functions enable an application to specify an OVERLAPPED structure that indicates where to position the file pointer before the read or write operation. The handle of the file being read from or written to must have been opened with the FILE_FLAG_OVERLAPPED flag. You can also create an event and put the handle in the OVERLAPPED structure; the wait functions can then be used to wait for the I/O operation to complete by waiting on the event handle.

An application can also wait on the file handle to synchronize the completion of an I/O operation, but doing so requires extreme caution. Each time an I/O operation is started, the operating system sets the file handle to the nonsignaled state. Each time an I/O operation is completed, the operating system sets the file handle to the signaled state. Therefore, if an application starts two I/O operations and waits on the file handle, there is no way to determine which operation is finished when the handle is set to the signaled state. If an application must perform multiple asynchronous I/O operations on a single file, it should wait on the event handle in the OVERLAPPED structure for each I/O operation, rather than on the file handle.

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.

The ReadFileEx and WriteFileEx functions enable an application to specify a routine to execute (see FileIOCompletionRoutine) when the asynchronous I/O request is completed.

For more information, see Synchronization and Overlapped Input and Output.


I/O Completion Ports

I/O completion ports are used with asynchronous I/O. The CreateIoCompletionPort function associates an I/O completion port with one or more file handles. When an asynchronous I/O operation started on a file handle associated with a completion port is completed, an I/O completion packet is queued to the port. This can be used to combine the synchronization point for multiple file handles into a single object.

A thread uses the GetQueuedCompletionStatus function to wait for a completion packet to be queued to the completion port, rather than waiting directly for the asynchronous I/O to complete. Threads that block their execution on a completion port are released in last-in-first-out (LIFO) order. This means that when a completion packet is queued to the completion port, the system releases the last thread to block its execution on the port.

When a thread calls GetQueuedCompletionStatus, it is associated with the specified completion port until it exits, specifies a different completion port, or frees the completion port. A thread can be associated with at most one completion port.

The most important property of a completion port is the concurrency value. The concurrency value of a completion port is specified when the completion port is created. This value limits the number of runnable threads associated with the completion port. When the total number of runnable threads associated with the completion port reaches the concurrency value, the system blocks the execution of any subsequent threads that specify the completion port until the number of runnable threads associated with the completion port drops below the concurrency value. The most efficient scenario occurs when there are completion packets waiting in the queue, but no waits can be satisfied because the port has reached its concurrency limit. In this case, when a running thread calls GetQueuedCompletionStatus, it will immediately pick up the queued completion packet. No context switches will occur, because the running thread is continually picking up completion packets and the other threads are unable to run.

The best value to pick for the concurrency value is the number of CPUs on the machine. If your transaction required a lengthy computation, a larger concurrency value will allow more threads to run. Each transaction will take longer to complete, but more transactions will be processed at the same time. It is easy to experiment with the concurrency value to achieve the best effect for your application.

The PostQueuedCompletionStatus function allows an application to queue its own special-purpose I/O completion packets to the completion port without starting an asynchronous I/O operation. This is useful for notifying worker threads of external events.

The completion port is freed when there are no more references to it. The completion port handle and every file handle associated with the completion port reference the completion port. All the handles must be closed to free the completion port. To close the port handle, call the CloseHandle function.


Getting Information About Files

There are a variety functions that you can use to obtain information about a file or the file system. These functions are discussed in the following topics:

  • File Attributes
  • File Type
  • File Date and Time
  • File Code Page
  • Volume Information


File Attributes

The GetFileInformationByHandle function retrieves information about a file and stores it in a structure of type BY_HANDLE_FILE_INFORMATION. This information includes creation time, file size, and attributes.

Eight characteristics called attributes may be associated with a file. The attributes can be one or more of the following values.

Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file or directory is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED | The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DEVICE | Reserved; do not use.
FILE_ATTRIBUTE_DIRECTORY | The handle identifies a directory.
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.
FILE_ATTRIBUTE_HIDDEN | The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL | The file or directory 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 Microsoft® Windows® 2000. Applications should not arbitrarily change this attribute.
FILE_ATTRIBUTE_READONLY | The file or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_REPARSE_POINT | The file has an associated reparse point.
FILE_ATTRIBUTE_SPARSE_FILE | The file is a sparse file.
FILE_ATTRIBUTE_SYSTEM | The file or directory is part of the operating system 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.

An application can retrieve the file attributes by using the GetFileAttributes or GetFileAttributesEx function. The CreateFile and SetFileAttributes functions can set many of the attributes. However, applications cannot set all attributes. For more information on how to set these attributes, see SetFileAttributes.


File Type

The GetFileType function retrieves the type of a file: disk, character (such as a console), pipe, or unknown. The GetBinaryType function determines whether a file is executable, and if so, what type of executable file it is. The GetFileSize function retrieves the size of a file.


File Date and Time

Applications can retrieve and set the date and time a file was created, last modified, or last accessed by using the GetFileTime and SetFileTime functions. For more information about file times, see Time.


File Code Page

The AreFileApisANSI function determines whether the file I/O functions are using the ANSI or OEM character set code page. The SetFileApisToANSI function causes the functions to use the ANSI code page. The SetFileApisToOEM function causes the functions to use the OEM code page.

By default, file I/O functions use ANSI file names. Functions exported by KERNEL32.DLL that accept or return file names are affected by the file code page setting.

Both SetFileApisToANSI and SetFileApisToOEM set the code page per process, rather than per thread or per computer.


Volume Information

The GetVolumeInformation function retrieves information about the file system on a given volume. This information includes the volume name, volume serial number, file system name, file system flags, maximum length of a file name, and so on. The SetVolumeLabel function sets the label of a file system volume.

The GetSystemDirectory and GetWindowsDirectory functions retrieve the paths to the system directory and the Windows directory, respectively.

The GetDiskFreeSpace function retrieves organizational information about a volume, including the number of bytes per sector, the number of sectors per cluster, the number of free clusters, and the total number of clusters. However, GetDiskFreeSpace cannot report volume sizes that are greater than 2 GB. To ensure that your application works with large capacity hard drives, use the GetDiskFreeSpaceEx function.

The GetDriveType function indicates whether the volume referenced by the specified drive letter is a removable, fixed, CD-ROM, RAM, or network drive.

The GetLogicalDrives function identifies the volumes present. The GetLogicalDriveStrings function retrieves a null-terminated string for each volume present. Use these strings whenever a root directory is required.


File and Directory Security

Windows NT/Windows 2000 security enables you to control access to file and directory objects stored on a secure file system, such as NTFS. For more information about security, see Access-Control Model.

You can specify a security descriptor for a file or directory when you call the CreateFile, CreateDirectory, or CreateDirectoryEx function. To retrieve the security descriptor of a file or directory object, call the GetNamedSecurityInfo or GetSecurityInfo function. To change the security descriptor of a file or directory object, call the SetNamedSecurityInfo or SetSecurityInfo function.

When a thread calls the CreateFile function to open a handle to a file or directory object, the thread requests a set of generic access rights to the object. The requested access rights determine the operations that the thread can perform with the returned handle. Before returning a handle to the object, CreateFile checks the thread's access token and the requested access rights against the DACL in the object's security descriptor.

For file and directory objects, GENERIC_READ access maps to the following standard and specific access rights.

Access right | Description
FILE_READ_ATTRIBUTES | Right to read file attributes.
FILE_READ_DATA | Right to read data from the file. For a directory, the right to list the contents of the directory.
FILE_READ_EA | Right to read extended attributes.
STANDARD_RIGHTS_READ | Includes READ_CONTROL, which is the right to read the information in the object's security descriptor, not including the information in the SACL.
SYNCHRONIZE | Right to specify a file handle in one of the wait functions. However, for asynchronous file I/O operations, you should wait on the event handle in an OVERLAPPED structure rather than using the file handle for synchronization.

For file and directory objects, GENERIC_WRITE access maps to the following standard and specific access rights.

Access right | Description
FILE_APPEND_DATA | Right to append data to the file. For a directory, the right to create a subdirectory.
FILE_WRITE_ATTRIBUTES | Right to write file attributes.
FILE_WRITE_DATA | Right to write data to the file. For a directory, the right to create a file in the directory.
FILE_WRITE_EA | Right to write extended attributes.
STANDARD_RIGHTS_WRITE | Includes READ_CONTROL, which is the right to read the information in the object's security descriptor, not including the information in the SACL.
SYNCHRONIZE | Right to specify a file handle in one of the wait functions. However, for asynchronous file I/O operations, you should wait on the event handle in an OVERLAPPED structure rather than using the file handle for synchronization.

You cannot use an access-denied ACE to deny only GENERIC_READ or only GENERIC_WRITE access to a file. This is because for file objects, the generic mappings for both GENERIC_READ or GENERIC_WRITE include the SYNCHRONIZE access right. If an ACE denies GENERIC_WRITE access to a trustee, and the trustee requests GENERIC_READ access, the request will fail because the request implicitly includes SYNCHRONIZE access which is implicitly denied by the ACE. And vice versa, too. Instead of using access-denied ACEs, use access-allowed ACEs to explicitly allow the permitted access rights.

You can request the ACCESS_SYSTEM_SECURITY access right to a file or directory object if you want to read or write the object's SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.


Using File I/O

The file I/O functions enable applications to access files regardless of the underlying file system. However, their functionality may vary depending on the operating system in use. If you have questions about a specific function, consult the reference information for that function.

For functions that manipulate files, the file names may be relative to the current directory. A file name is relative to the current directory if it does not begin with a disk designator or directory name separator, such as a backslash (\). If the file name begins with a disk designator, it is a full path.

The examples in this section illustrate how to perform the following tasks:

  • Creating and opening files
  • Reading, writing, and locking files
  • Creating and using a temporary file
  • Searching for files and changing file attributes
  • Monitoring changes in a directory or directory tree
  • Testing for the end of the file
  • Retrieving a file pointer


Creating and Opening Files

You can use the CreateFile function to create a new file or open an existing file. You must specify the file name, preferred access, share mode, creation instructions, and attributes.

In the following example, CreateFile opens an existing file for reading.

HANDLE hFile;

hFile = CreateFile("MYFILE.TXT",           // open MYFILE.TXT
                GENERIC_READ,              // open for reading
                FILE_SHARE_READ,           // share for reading
                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 file.");   // process error
}

In this example, CreateFile succeeds only if a file named MYFILE.TXT already exists in the current directory. An application should check the return value of CreateFile before attempting to use the handle to access the file. If an error occurs, the application should use the GetLastError function to get extended error information and respond accordingly.

A file must be closed before it can be deleted. The following lines close and delete the MYFILE.TXT file.

CloseHandle(hFile);
DeleteFile("MYFILE.TXT");

In the following example, CreateFile creates a new file and opens it for writing.

HANDLE hFile;

hFile = CreateFile("MYFILE.TXT",           // create MYFILE.TXT
             GENERIC_WRITE,                // open for writing
             0,                            // do not share
             NULL,                         // no security
             CREATE_ALWAYS,                // overwrite existing
             FILE_ATTRIBUTE_NORMAL |       // normal file
             FILE_FLAG_OVERLAPPED,         // asynchronous I/O
             NULL);                        // no attr. template

if (hFile == INVALID_HANDLE_VALUE)
{
    ErrorHandler("Could not open file.");  // process error
}

In addition to the standard attributes (read only, hidden, system, and so on), you can also specify security attributes by including a pointer to a SECURITY_ATTRIBUTES structure as the fourth parameter. However, the underlying file system must support security for these attributes for them to have any effect. For more information about security attributes, see Access Control.


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\n",
            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\n", 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\n");
                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\n",
                    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);


Creating and Using a Temporary File

The following example copies one file to another. The second file is an uppercase version of the first file.

The application opens the ORIGINAL.TXT file by using CreateFile. The application then retrieves a temporary file name with the GetTempFileName function and uses CreateFile to create the temporary file. The application reads 4K blocks into a buffer, converts the buffer contents to uppercase, and writes the converted buffer to the temporary file. When all of ORIGINAL.TXT has been written to the temporary file, the application closes both files and renames the temporary file to ALLCAPS.TXT by using the MoveFile function.

HANDLE hFile;

HANDLE hTempFile;

DWORD  dwBytesRead, dwBytesWritten, dwPos;

char szTempName[MAX_PATH];

char buffer[4096];

// Open the existing file.

hFile = CreateFile("ORIGINAL.TXT",  // file name
    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 file."); // process error
}

// Create a temporary file.

GetTempFileName("\\TEMP", // dir. for temp. files
    "NEW",                // temp. file name prefix
    0,                    // create unique name
    szTempName);          // buffer for name

hTempFile = CreateFile((LPTSTR) szTempName,  // file name
    GENERIC_READ | GENERIC_WRITE, // open for read/write
    0,                            // do not share
    NULL,                         // no security
    CREATE_ALWAYS,                // overwrite existing file
    FILE_ATTRIBUTE_NORMAL,        // normal file
    NULL);                        // no attr. template

if (hTempFile == INVALID_HANDLE_VALUE)
{
    ErrorHandler("Could not create temporary file.");
}

// Read 4K blocks to the buffer.
// Change all characters in the buffer to uppercase.
// Write the buffer to the temporary file.

do
{
    if (ReadFile(hFile, buffer, 4096,
        &dwBytesRead, NULL))
    {
        CharUpperBuff(buffer, dwBytesRead);

        WriteFile(hTempFile, buffer, dwBytesRead,
            &dwBytesWritten, NULL);
    }
} while (dwBytesRead == 4096);

// Close both files.

CloseHandle(hFile);
CloseHandle(hTempFile);

// Move the temporary file to the new text file.

if (!MoveFile(szTempName, "ALLCAPS.TXT"))
{
    ErrorHandler("Could not move temp. file.");
}


Searching for Files and Changing File Attributes

The following example copies all text files in the current directory to a new directory of read-only files named \TEXTRO. Files in the new directory are changed to read only, if necessary.

The application uses the GetCurrentDirectory function to retrieve the current directory path. This function is also used to return to the current directory after changing to the \TEXTRO directory.

The application then creates the \TEXTRO directory by using the CreateDirectory function.

The application searches the current directory for all .TXT files by using the FindFirstFile and FindNextFile functions. Each .TXT file is copied to the \TEXTRO directory. After a file is copied, the GetFileAttributes function determines whether the file is read only. If the file is not read only, the application changes directories to \TEXTRO and converts the copied file to read only by using the SetFileAttributes function.

After all .TXT files in the current directory have been copied, the application closes the search handle by using the FindClose function.

WIN32_FIND_DATA FileData;
HANDLE hSearch;
DWORD dwAttrs;
char szDirPath[] = "c:\\TEXTRO\\";
char szNewPath[MAX_PATH];
char szHome[MAX_PATH];

BOOL fFinished = FALSE;

// Create a new directory.

if (!CreateDirectory(szDirPath, NULL))
{
    ErrorHandler("Couldn't create new directory.");
}

// Start searching for .TXT files in the current directory.

hSearch = FindFirstFile("*.txt", &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
    ErrorHandler("No .TXT files found.");
}

// Copy each .TXT file to the new directory
// and change it to read only, if not already.

while (!fFinished)
{
    lstrcpy(szNewPath, szDirPath);
    lstrcat(szNewPath, FileData.cFileName);
    if (CopyFile(FileData.cFileName, szNewPath, FALSE))
    {
        dwAttrs = GetFileAttributes(FileData.cFileName);
        if (!(dwAttrs & FILE_ATTRIBUTE_READONLY))
        {
            SetFileAttributes(szNewPath,
                dwAttrs | FILE_ATTRIBUTE_READONLY);
        }
    }
    else
    {
        ErrorHandler("Couldn't copy file.");
    }

    if (!FindNextFile(hSearch, &FileData))
    {
        if (GetLastError() == ERROR_NO_MORE_FILES)
        {
            MessageBox(hwnd, "No more .TXT files.",
                "Search completed.", MB_OK);
            fFinished = TRUE;
        }
        else
        {
            ErrorHandler("Couldn't find next file.");
        }
    }
}

// Close the search handle.

if (!FindClose(hSearch))
{
    ErrorHandler("Couldn't close search handle.");
}


Monitoring Changes in a Directory or Directory Tree

The following example monitors the directory tree starting at C:\ for directory name changes. It also monitors the C:\WINDOWS directory for file name changes.

The example uses the FindFirstChangeNotification function to create two notification handles and the WaitForMultipleObjects function to wait on the handles. Whenever a directory is created or deleted in the tree starting at C:\ , the example updates the entire directory tree. Whenever a file is created or deleted in the C:\WINDOWS directory, the example refreshes the WINDOWS directory. The FindNextChangeNotification function restarts the change notification each time the example processes a change.

DWORD dwWaitStatus;
HANDLE dwChangeHandles[2];

// Watch the C:\WINDOWS directory for file creation and
// deletion.

dwChangeHandles[0] = FindFirstChangeNotification(
    "C:\\WINDOWS",                 // directory to watch
    FALSE,                         // do not watch the subtree
    FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes

if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
    ExitProcess(GetLastError());

// Watch the C:\ subtree for directory creation and
// deletion.

dwChangeHandles[1] = FindFirstChangeNotification(
    "C:\\",                        // directory to watch
    TRUE,                          // watch the subtree
    FILE_NOTIFY_CHANGE_DIR_NAME);  // watch dir. name changes

if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
    ExitProcess(GetLastError());

// Change notification is set. Now wait on both notification
// handles and refresh accordingly.

while (TRUE)
{

    // Wait for notification.

    dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles,
        FALSE, INFINITE);

    switch (dwWaitStatus)
    {
        case WAIT_OBJECT_0:

        // A file was created or deleted in C:\WINDOWS.
        // Refresh this directory and restart the
        // change notification. RefreshDirectory is an
        // application-defined function.

            RefreshDirectory("C:\\WINDOWS")
            if ( FindNextChangeNotification(
                    dwChangeHandles[0]) == FALSE )
                ExitProcess(GetLastError());
            break;

        case WAIT_OBJECT_0 + 1:

        // A directory was created or deleted in C:\.
        // Refresh the directory tree and restart the
        // change notification. RefreshTree is an
        // application-defined function.

            RefreshTree("C:\\");
            if (FindNextChangeNotification(
                    dwChangeHandles[1]) == FALSE)
                ExitProcess(GetLastError());
            break;

        default:
            ExitProcess(GetLastError());
    }
}


Testing for the End of the File

The ReadFile function checks for the end-of-file condition (eof) differently for synchronous and asynchronous read operations. When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets the variable pointed to by lpNumberOfBytesRead to zero. An asynchronous read operation can encounter the end of a file during the initiating call to ReadFile or during subsequent asynchronous operation.

The test for end-of-file during a synchronous read operation is simple, as shown in the following example:

// Attempt a synchronous read operation
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);

// Check for eof
if (bResult &&  nBytesRead == 0, )
{
    // We're at the end of the file
}

The test for end-of-file during an asynchronous read operation is more difficult. There are three end-of-file indicators for asynchronous read operations:

  • ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF.
  • ReadFile returns FALSE and GetLastError returns ERROR_IO_PENDING.
  • GetOverlappedResult returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

The following example shows how to test for an end-of-file during an asynchronous read operation:

// Attempt to initiate an asynchronous read operation.
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL);

// Check if there was a problem.
if (!bResult)
{
    switch (dwError = GetLastError())
    {
        case ERROR_HANDLE_EOF:
        // At the end of the file.
            break;
        case ERROR_IO_PENDING:
        // I/O pending.
           break;
    }
}

// Check on an asynchronous read operation.
bResult = GetOverlappedResult(hFile, &gOverlapped, &nBytesRead, TRUE);

// Check if there was a problem.
if (!bResult)
{
    switch (dwError = GetLastError())
    {
        case ERROR_HANDLE_EOF:
        // At the end of the file
    }
}


Retrieving a File Pointer

The SetFilePointer function can be used to query the current file pointer position, by specifying a move method of FILE_CURRENT and a distance of zero.

HANDLE hFile;

DWORD dwCurrentFilePosition;

dwCurrentFilePosition = SetFilePointer(
    hFile, // must have GENERIC_READ and/or GENERIC_WRITE
    0,     // do not move pointer
    NULL,  // hFile is not large enough to need this pointer
    FILE_CURRENT);  // provides offset from current position

The following macro can be used to obtain the current file pointer position for files smaller than 2 gigabytes in size:

    #define GetFilePointer(hFile) SetFilePointer(hFile, 0, NULL, FILE_CURRENT)

To get the current file positions on larger files, use the following:

    #define GetVLFilePointer(hFile, lpPositionHigh) \
        (*lpPositionHigh = 0, \
        SetFilePointer(hFile, 0, lpPositionHigh, FILE_CURRENT))

where lpPositionHigh is a value of type PLONG. The high order long word of the current file position will be returned in lpPositionHigh.


File I/O Reference

The following elements are used with file I/O.

  • File I/O Functions
  • File I/O Structures
  • File I/O Enumeration Types


File I/O Functions

The following functions are used with files.

Function | Description
AreFileApisANSI | Determines whether the file I/O functions are using the ANSI or OEM character set code page.
CancelIo | Cancels all pending I/O operations that were issued by the calling thread for the specified file handle.
CloseHandle | Closes an open object handle.
CopyFile | Copies an existing file to a new file.
CopyFileEx | Copies an existing file to a new file.
CopyProgressRoutine | An application-defined callback function used with CopyFileEx and MoveFileWithProgress.
CreateDirectory | Creates a new directory.
CreateDirectoryEx | Creates a new directory with the attributes of a specified template directory.
CreateFile | Creates or opens a file object.
CreateIoCompletionPort | Creates and I/O completion port or associates an instance of an opened file with a newly created or an existing I/O completion port.
DefineDosDevice | Defines, redefines, or deletes MS-DOS device names.
DeleteFile | Deletes an existing file.
FileIOCompletionRoutine | An application-defined callback function used with ReadFileEx and WriteFileEx.
FindClose | Closes the specified search handle.
FindCloseChangeNotification | Stops change notification handle monitoring.
FindFirstChangeNotification | Creates a change notification handle.
FindFirstFile | Searches a directory for a file whose name matches the specified file name.
FindFirstFileEx | Searches a directory for a file whose name and attributes match those specified.
FindNextChangeNotification | Requests that the operating system signal a change notification handle the next time it detects an appropriate change.
FindNextFile | Continues a file search.
FlushFileBuffers | Clears the buffers for the specified file and causes all buffered data to be written to the file.
GetBinaryType | Determines whether a file is executable.
GetCurrentDirectory | Retrieves the current directory for the current process.
GetDiskFreeSpace | Retrieves information about the specified disk, including the amount of free space on the disk.
GetDiskFreeSpaceEx | Retrieves information about the specified disk, including the amount of free space on the disk.
GetDriveType | Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.
GetFileAttributes | Retrieves attributes for a specified file or directory.
GetFileAttributesEx | Retrieves attributes for a specified file or directory.
GetFileInformationByHandle | Retrieves file information for a specified file.
GetFileSize | Retrieves the size of a specified file.
GetFileSizeEx | Retrieves the size of a specified file.
GetFileType | Retrieves the file type of the specified file.
GetFullPathName | Retrieves the full path and file name of a specified file.
GetLogicalDrives | Returns a bitmask representing the currently available disk drives.
GetLogicalDriveStrings | Fills a buffer with strings that specify valid drives in the system.
GetLongPathName | Converts the specified path to its long form.
GetQueuedCompletionStatus | Attempts to dequeue an I/O completion packet from a specified I/O completion port.
GetShortPathName | Retrieves the short path form of a specified input path.
GetTempFileName | Creates a name for a temporary file.
GetTempPath | Retrieves the path of the directory designated for temporary files.
LockFile | Locks a region in an open file.
LockFileEx | Locks a region in an open file for shared or exclusive access.
MoveFile | Moves an existing file or a directory.
MoveFileEx | Moves an existing file or a directory.
MoveFileWithProgress | Moves a file or directory.
PostQueuedCompletionStatus | Posts an I/O completion packet to an I/O completion port.
QueryDosDevice | Retrieves information about MS-DOS device names.
ReadDirectoryChangesW | Retrieves information describing the changes occurring within a directory.
ReadFile | Reads data from a file, starting at the specified position.
ReadFileEx | Reads data from a file asynchronously.
ReadFileScatter | Reads data from a file and stores the data into a set of buffers.
RemoveDirectory | Deletes an existing empty directory.
ReplaceFile | Replaces one file with another file.
SearchPath | Searches for the specified file.
SetCurrentDirectory | Changes the current directory for the current process.
SetEndOfFile | Moves the end-of-file position for the specified file.
SetFileApisToANSI | Causes the file I/O functions to use the ANSI character set code page.
SetFileApisToOEM | Causes the file I/O functions to use the OEM character set code page.
SetFileAttributes | Sets a file's attributes.
SetFilePointer | Moves the file pointer of an open file.
SetFilePointerEx | Moves the file pointer of an open file.
SetFileSecurity | Sets the security of a file or directory object.
SetFileShortName | Sets the valid data length of the specified file.
SetFileValidData | Sets the valid data length of the specified file.
SetVolumeLabel | Sets the label of a file system volume.
UnlockFile | Unlocks a previously locked region in an open file.
UnlockFileEx | Unlocks a previously locked region in an open file.
WriteFile | Writes data to a file.
WriteFileEx | Writes data to a file asynchronously.
WriteFileGather | Gathers data from a set of buffers and writes the data to a file.

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of Windows.

_hread
_hwrite
_lclose
_lcreat
_llseek
_lopen
_lread
_lwrite
OpenFile


_hread

The _hread function reads data from the specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the ReadFile function.

long _hread(
  HFILE hFile,      // handle to file
  LPVOID lpBuffer,  // read data buffer
  long lBytes       // length of read data buffer
);

Parameters

hFile
[in] Handle to the specified file.
lpBuffer
[out] Pointer to a buffer that contains the data read from the file.
lBytes
[in] Specifies the number of bytes to be read from the file.

Return Values

The return value indicates the number of bytes actually read from the file. If the number of bytes read is less than lBytes, the function has reached the end of file (EOF) before reading the specified number of bytes.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _hwrite, ReadFile, SetErrorMode


_hwrite

The _hwrite function writes data to the specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the WriteFile function.

long _hwrite(
  HFILE hFile,      // handle to file
  LPCSTR lpBuffer,  // write data buffer
  long lBytes       // number of bytes to write
);

Parameters

hFile
[in] Handle to the specified file.
lpBuffer
[in] Pointer to a buffer that contains the data to be written to the file.
lBytes
[in] Specifies the number of bytes to be written to the file.

Return Values

If the function succeeds, the return value indicates the number of bytes actually written to the file.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _hread, SetErrorMode, WriteFile


_lclose

The _lclose function closes the specified file so that it is no longer available for reading or writing.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the CloseHandle function.

HFILE _lclose(
  HFILE hFile   // handle to file
);

Parameters

hFile
[in/out] Handle to the file to be closed. This handle is returned by the function that created or last opened the file.

Return Values

If the function succeeds, the return value is zero.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CloseHandle, CreateFile, _lopen


_lcreat

The _lcreat function creates or opens a specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the CreateFile function.

HFILE _lcreat(
  LPCSTR lpPathName,  // pointer to name of file to open
  int iAttribute      // file attribute
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that names the file to be opened. The string must consist of characters from the ANSI character set.
iAttribute
[in] Specifies the file attributes. This parameter must be one of the following values.
Value | Meaning
0 | Normal (can be read from or written to without restriction).
1 | Read only (cannot be opened for write)
2 | Hidden (not found by directory search)
4 | System (not found by directory search)

Return Values

If the function succeeds, the return value is a file handle.

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

Remarks

If the file does not exist, the _lcreat function creates a new file and opens it for writing. If the file exists, _lcreat truncates the file size to zero and opens it for reading and writing. When the function opens the file, the pointer is set to the beginning of the file.

The _lcreat function should be used carefully. It can open any file, even one already opened by another function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, _lopen


_llseek

The _llseek function repositions the file pointer in a previously opened file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the SetFilePointer function.

LONG _llseek(
  HFILE hFile,  // handle to file
  LONG lOffset, // number of bytes to move
  int iOrigin   // starting position
);

Parameters

hFile
[in] Handle to the file.
lOffset
[in] Specifies the number of bytes the file pointer is to be moved.
iOrigin
[in] Specifies the starting position and direction of the file pointer. This parameter must be one of the following values.
Value | Meaning
FILE_BEGIN | Moves the file pointer lOffset bytes from the beginning of the file.
FILE_CURRENT | Moves the file pointer lOffset bytes from its current position.
FILE_END | Moves the file pointer lOffset bytes from the end of the file.

Return Values

If the function succeeds, the return value specifies the new offset of the pointer, in bytes, from the beginning of the file.

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

Remarks

When a file is initially opened, the file pointer is set to the beginning of the file. The _llseek function moves the pointer an arbitrary amount without reading data, which facilitates random access to the file's contents.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _lopen, SetFilePointer


_lopen

The _lopen function opens an existing file and sets the file pointer to the beginning of the file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the CreateFile function.

HFILE _lopen(
  LPCSTR lpPathName,  // pointer to name of file to open
  int iReadWrite      // file access mode
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that names the file to open. The string must consist of characters from the ANSI character set.
iReadWrite
[in] Specifies the modes in which to open the file. This parameter consists of one access mode and an optional share mode. The access mode must be one of the following values.
Value | Meaning
OF_READ | Opens the file for reading only.
OF_READWRITE | Opens the file for reading and writing.
OF_WRITE | Opens the file for writing only.

The share mode can be one of the following values.
Value | Meaning
OF_SHARE_COMPAT | Opens the file in compatibility mode, enabling any process on a given computer to open the file any number of times. If the file has been opened by using any of the other share modes, _lopen fails.
OF_SHARE_DENY_NONE | Opens the file without denying other processes read or write access to the file. If the file has been opened in compatibility mode by any other process, _lopen fails.
OF_SHARE_DENY_READ | Opens the file and denies other processes read access to the file. If the file has been opened in compatibility mode or for read access by any other process, _lopen fails.
OF_SHARE_DENY_WRITE | Opens the file and denies other processes write access to the file. If the file has been opened in compatibility mode or for write access by any other process, _lopen fails.
OF_SHARE_EXCLUSIVE | Opens the file in exclusive mode, denying other processes both read and write access to the file. If the file has been opened in any other mode for read or write access, even by the current process, _lopen fails.

Return Values

If the function succeeds, the return value is a file handle.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile


_lread

The _lread function reads data from the specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the ReadFile function.

UINT _lread(
  HFILE hFile,      // handle to file
  LPVOID lpBuffer,  // pointer to buffer for read data
  UINT uBytes       // length, in bytes, of data buffer
);

Parameters

hFile
[in] Handle to the specified file.
lpBuffer
[out] Pointer to a buffer that contains the data read from the file.
uBytes
[in] Specifies the number of bytes to be read from the file.

Return Values

The return value indicates the number of bytes actually read from the file. If the number of bytes read is less than uBytes, the function has reached the end of file (EOF) before reading the specified number of bytes.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _lwrite, ReadFile, SetErrorMode


_lwrite

The _lwrite function writes data to the specified file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the WriteFile function.

UINT _lwrite(
  HFILE hFile,      // handle to file
  LPCSTR lpBuffer,  // write data buffer
  UINT uBytes       // number of bytes to write
);

Parameters

hFile
[in] Handle to the specified file.
lpBuffer
[in] Pointer to a buffer that contains the data to write to the file.
uBytes
[in] Specifies the number of bytes to be written to the file.

Return Values

If the function succeeds, the return value indicates the number of bytes actually written to the file.

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

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _lread, SetErrorMode, WriteFile


AreFileApisANSI

The AreFileApisANSI function determines whether the file I/O functions are using the ANSI or OEM character set code page. This function is useful for 8-bit console input and output operations.

BOOL AreFileApisANSI(VOID);

Parameters

This function has no parameters.

Return Values

If the set of file I/O functions is using the ANSI code page, the return value is nonzero.

If the set of file I/O functions is using the OEM code page, the return value is zero.

Remarks

The SetFileApisToOEM function causes a set of file I/O functions to use the OEM code page. The SetFileApisToANSI function causes the same set of file I/O functions to use the ANSI code page. Use the AreFileApisANSI function to determine which code page the set of file I/O functions is currently using. For a discussion of these functions' usage, please refer to the Remarks sections of SetFileApisToOEM and SetFileApisToANSI.

The file I/O functions whose code page is ascertained by AreFileApisANSI are those functions exported by KERNEL32.DLL that accept or return a file name.

The functions SetFileApisToOEM and SetFileApisToANSI set the code page for a process, so AreFileApisANSI returns a value indicating the code page of an entire process.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, SetFileApisToANSI, SetFileApisToOEM


CancelIo

The CancelIo function cancels all pending input and output (I/O) operations that were issued by the calling thread for the specified file handle. The function does not cancel I/O operations issued for the file handle by other threads.

BOOL CancelIo(
  HANDLE hFile  // handle to file
);

Parameters

hFile
[in] Handle to a file. The function cancels all pending I/O operations for this file handle.

Return Values

If the function succeeds, the return value is nonzero. All pending I/O operations issued by the calling thread for the file handle were successfully canceled.

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

Remarks

If there are any I/O operations in progress for the specified file handle, and they were issued by the calling thread, the CancelIo function cancels them.

Note that the I/O operations must have been issued as overlapped I/O. If they were not, the I/O operations would not have returned to allow the thread to call the CancelIo function. Calling the CancelIo function with a file handle that was not opened with FILE_FLAG_OVERLAPPED does nothing.

All I/O operations that are canceled will complete with the error ERROR_OPERATION_ABORTED. All completion notifications for the I/O operations will occur normally.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, DeviceIoControl, LockFileEx, ReadDirectoryChangesW, ReadFile, ReadFileEx, WriteFile, WriteFileEx


CopyFile

The CopyFile function copies an existing file to a new file.

The CopyFileEx function provides two additional capabilities. CopyFileEx can call a specified callback function each time a portion of the copy operation is completed, and CopyFileEx can be canceled during the copy operation.

BOOL CopyFile(
  LPCTSTR lpExistingFileName, // name of an existing file
  LPCTSTR lpNewFileName,      // name of new file
  BOOL bFailIfExists          // operation if file exists
);

Parameters

lpExistingFileName
[in] Pointer to a null-terminated string that specifies the name of an existing file.

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

lpNewFileName
[in] Pointer to a null-terminated string that specifies the name of the new file.

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

bFailIfExists
[in] Specifies how this operation is to proceed if a file of the same name as that specified by lpNewFileName already exists. If this parameter is TRUE and the new file already exists, the function fails. If this parameter is FALSE and the new file already exists, the function overwrites the existing file and succeeds.

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

Security attributes for the existing file are not copied to the new file.

File attributes for the existing file are copied to the new file. For example, if an existing file has the FILE_ATTRIBUTE_READONLY file attribute, a copy created through a call to CopyFile will also have the FILE_ATTRIBUTE_READONLY file attribute.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CopyFileEx, CreateFile, MoveFile


CopyFileEx

The CopyFileEx function copies an existing file to a new file. This function preserves extended attributes, OLE structured storage, NTFS alternate data streams, and file attributes. Security attributes for the existing file are not copied to the new file.

BOOL CopyFileEx(
  LPCTSTR lpExistingFileName,           // name of existing file
  LPCTSTR lpNewFileName,                // name of new file
  LPPROGRESS_ROUTINE lpProgressRoutine, // callback function
  LPVOID lpData,                        // callback parameter
  LPBOOL pbCancel,                      // cancel status
  DWORD dwCopyFlags                     // copy options
);

Parameters

lpExistingFileName
[in] Pointer to a null-terminated string that specifies the name of an existing file.

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

lpNewFileName
[in] Pointer to a null-terminated string that specifies the name of the new file.

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

lpProgressRoutine
[in] Specifies the address of a callback function of type LPPROGRESS_ROUTINE that is called each time another portion of the file has been copied. This parameter can be NULL. For more information on the progress callback function, see CopyProgressRoutine.
lpData
[in] Specifies an argument to be passed to the callback function. This parameter can be NULL.
pbCancel
[in] Pointer to a Boolean variable that can be used to cancel the operation. If this flag is set to TRUE during the copy operation, the operation is canceled.
dwCopyFlags
[in] Specifies how the file is to be copied. This parameter can be a combination of the following values.
Value | Meaning
COPY_FILE_FAIL_IF_EXISTS | The copy operation fails immediately if the target file already exists.
COPY_FILE_RESTARTABLE | Progress of the copy is tracked in the target file in case the copy fails. The failed copy can be restarted at a later time by specifying the same values for lpExistingFileName and lpNewFileName as those used in the call that failed.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File I/O Overview, File I/O Functions, CreateFile, CopyFile, CopyProgressRoutine, MoveFile


CopyProgressRoutine

The CopyProgressRoutine function is an application-defined callback function used with the CopyFileEx and MoveFileWithProgress functions. It is called when a portion of a copy or move operation is completed. The LPPROGRESS_ROUTINE type defines a pointer to this callback function. CopyProgresRoutine is a placeholder for the application-defined function name.

DWORD CALLBACK CopyProgressRoutine(
  LARGE_INTEGER TotalFileSize,          // file size
  LARGE_INTEGER TotalBytesTransferred,  // bytes transferred
  LARGE_INTEGER StreamSize,             // bytes in stream
  LARGE_INTEGER StreamBytesTransferred, // bytes transferred for stream
  DWORD dwStreamNumber,                 // current stream
  DWORD dwCallbackReason,               // callback reason
  HANDLE hSourceFile,                   // handle to source file
  HANDLE hDestinationFile,              // handle to destination file
  LPVOID lpData                         // from CopyFileEx
);

Parameters

TotalFileSize
[in] Specifies the total size of the file, in bytes.
TotalBytesTransferred
[in] Specifies the total number of bytes transferred from the source file to the destination file since the copy operation began.
StreamSize
[in] Specifies the total size of the current file stream, in bytes.
StreamBytesTransferred
[in] Specifies the total number of bytes in the current stream that have been transferred from the source file to the destination file since the copy operation began.
dwStreamNumber
[in] Handle to the current stream. The first time CopyProgressRoutine is called, the stream number is 1.
dwCallbackReason
[in] Specifies the reason that CopyProgressRoutine was called. This parameter can be one of the following values.
Value | Meaning
CALLBACK_CHUNK_FINISHED | Another part of the data file was copied.
CALLBACK_STREAM_SWITCH | Another stream was created and is about to be copied. This is the callback reason given when the callback routine is first invoked.

hSourceFile
[in] Handle to the source file.
hDestinationFile
[in] Handle to the destination file
lpData
[in] The argument passed to CopyProgressRoutine by the CopyFileEx or MoveFileWithProgress function.

Return Values

The CopyProgressRoutine function should return one of the following values.

Value | Meaning
PROGRESS_CONTINUE | Continue the copy operation.
PROGRESS_CANCEL | Cancel the copy operation and delete the destination file.
PROGRESS_STOP | Stop the copy operation. It can be restarted at a later time.
PROGRESS_QUIET | Continue the copy operation, but stop invoking CopyProgressRoutine to report progress.

Remarks

An application can use this information to display a progress bar that shows the total number of bytes copied as a percent of the total file size.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Functions, CopyFileEx, MoveFileWithProgress


CreateDirectory

The CreateDirectory function creates a new directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory.

To specify a template directory, use the CreateDirectoryEx function.

BOOL CreateDirectory(
  LPCTSTR lpPathName,                         // directory name
  LPSECURITY_ATTRIBUTES lpSecurityAttributes  // SD
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the path of the directory to be created.

There is a default string size limit for paths of 248 characters. This limit is related to how the CreateDirectory function parses paths.

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

lpSecurityAttributes
Windows NT/2000 or later: [in] Pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory. If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The target file system must support security on files and directories for this parameter to have an effect.

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

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.

Windows NT/2000 or later: An application can obtain a handle to a directory by calling CreateFile with the FILE_FLAG_BACKUP_SEMANTICS flag set. For a code example, see CreateFile.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CreateDirectoryEx, CreateFile, RemoveDirectory, SECURITY_ATTRIBUTES


CreateDirectoryEx

The CreateDirectoryEx function creates a new directory with the attributes of a specified template directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory. The new directory retains the other attributes of the specified template directory.

BOOL CreateDirectoryEx(
  LPCTSTR lpTemplateDirectory,               // template directory
  LPCTSTR lpNewDirectory,                    // directory name
  LPSECURITY_ATTRIBUTES lpSecurityAttributes // SD
);

Parameters

lpTemplateDirectory
[in] Pointer to a null-terminated string that specifies the path of the directory to use as a template when creating the new directory.

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

lpNewDirectory
[in] Pointer to a null-terminated string that specifies the path of the directory to be created.

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

lpSecurityAttributes
Windows NT/2000 or later: [in] Pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory. If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The target file system must support security on files and directories for this parameter to have an effect.

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

The CreateDirectoryEx function allows you to create directories that inherit stream information from other directories. This function is useful, for example, when dealing with Macintosh directories, which have a resource stream that is needed to properly identify directory contents as an attribute.

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.

Windows NT/2000 or later: You can obtain a handle to a directory by calling the CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag set. See CreateFile for a code example.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CreateDirectory, CreateFile, RemoveDirectory, SECURITY_ATTRIBUTES


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 (Windows NT/2000 only)
  • 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 or later: 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.
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

dwShareMode
[in] Specifies how the object can be shared. If dwShareMode is 0, the object cannot be shared. Subsequent open operations on the object will fail, until the handle is closed.

To share the object, use a combination of one or more of the following values.
Value | Meaning
FILE_SHARE_DELETE | Windows NT/2000 or later: 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.

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 or later: 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.
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.

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

  • 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_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 or later: 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_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.

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.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

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:

  • 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 or later: 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 or later: 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.

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 or later: 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:
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.

  • The lpFileName string should be \\.\x: to open a floppy drive x or a partition x on a hard disk. For example:
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 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 or later: 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.

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/98/Me: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND. Windows NT/2000 or later: 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 or later: 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.

For example, see Creating and Opening Files.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

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


CreateIoCompletionPort

The CreateIoCompletionPort function can associate an instance of an opened file with a newly created or an existing input/output (I/O) completion port, or it can create an I/O completion port without associating it with a file.

Associating an instance of an opened file with an I/O completion port lets an application receive notification of the completion of asynchronous I/O operations involving that file.

HANDLE CreateIoCompletionPort (
  HANDLE FileHandle,              // handle to file
  HANDLE ExistingCompletionPort,  // handle to I/O completion port
  ULONG_PTR CompletionKey,        // completion key
  DWORD NumberOfConcurrentThreads // number of threads to execute concurrently
);

Parameters

FileHandle
[in] Handle to a file opened for overlapped I/O completion. You must specify the FILE_FLAG_OVERLAPPED flag when using the CreateFile function to obtain the handle.

If FileHandle specifies INVALID_HANDLE_VALUE, CreateIoCompletionPort creates an I/O completion port without associating it with a file. In this case, the ExistingCompletionPort parameter must be NULL and the CompletionKey parameter is ignored.

ExistingCompletionPort
[in] Handle to the I/O completion port.

If this parameter specifies an existing completion port, the function associates it with the file specified by the FileHandle parameter. The function returns the handle of the existing completion port; it does not create a new I/O completion port.

If this parameter is NULL, the function creates a new I/O completion port and associates it with the file specified by FileHandle. The function returns the handle to the new I/O completion port.

CompletionKey
[in] Per-file completion key that is included in every I/O completion packet for the specified file.
NumberOfConcurrentThreads
[in] Maximum number of threads that the operating system allows to concurrently process I/O completion packets for the I/O completion port. If this parameter is zero, the system allows as many concurrently running threads as there are processors in the system.

Although any number of threads can call the GetQueuedCompletionStatus function to wait for an I/O completion port, each thread is associated with only one completion port at a time. That port is the port that was last checked by the thread.

When a packet is queued to a port, the system first checks how many threads associated with the port are running. If the number of threads running is less than the value of NumberOfConcurrentThreads, then one of the waiting threads is allowed to process the packet. When a running thread completes its processing, it calls GetQueuedCompletionStatus again, at which point the system can allow another waiting thread to process a packet.

The system also allows a waiting thread to process a packet if a running thread enters any wait state. When the thread in the wait state begins running again, there may be a brief period when the number of active threads exceeds the NumberOfConcurrentThreads value. However, the system quickly reduces the number by not allowing any new active threads until the number of active threads falls below the specified value.

Return Values

If the function succeeds, the return value is the handle to the I/O completion port that is associated with the specified file.

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

Remarks

The I/O system can be instructed to send I/O completion notification packets to I/O completion ports, where they are queued. The CreateIoCompletionPort function provides this functionality.

After an instance of an open file is associated with an I/O completion port, it cannot be used in the ReadFileEx or WriteFileEx function. It is best not to share such an associated file through either handle inheritance or a call to the DuplicateHandle function. Operations performed with such duplicate handles generate completion notifications.

When you perform an I/O operation with a file handle that has an associated I/O completion port, the I/O system sends a completion notification packet to the completion port when the I/O operation completes. The I/O completion port places the completion packet in a first-in-first-out queue. Use the GetQueuedCompletionStatus function to retrieve these queued I/O completion packets.

Threads in the same process can use the PostQueuedCompletionStatus function to place I/O completion notification packets in a completion port's queue. By doing so, you can use the port to receive communications from other threads of the process, in addition to receiving I/O completion notification packets from the I/O system.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, DuplicateHandle, GetQueuedCompletionStatus, PostQueuedCompletionStatus, ReadFileEx, WriteFileEx


DefineDosDevice

The DefineDosDevice function defines, redefines, or deletes MS-DOS device names.

BOOL DefineDosDevice(
  DWORD dwFlags,         // options
  LPCTSTR lpDeviceName,  // device name
  LPCTSTR lpTargetPath   // path string
);

Parameters

dwFlags
[in] Specifies several controllable aspects of the DefineDosDevice function. This parameter can be one or more of the following values.
Value | Meaning
DDD_RAW_TARGET_PATH | If this value is specified, the function does not convert the lpTargetPath string from an MS-DOS path to a path, but takes it as is.
DDD_REMOVE_DEFINITION If this value is specified, the function removes the specified definition for the specified device. To determine which definition to remove, the function walks the list of mappings for the device, looking for a match of lpTargetPath against a prefix of each mapping associated with this device. The first mapping that matches is the one removed, and then the function returns.

If lpTargetPath is NULL or a pointer to a NULL string, the function will remove the first mapping associated with the device and pop the most recent one pushed. If there is nothing left to pop, the device name will be removed.

If this value is NOT specified, the string pointed to by the lpTargetPath parameter will become the new mapping for this device.
DDD_EXACT_MATCH_ON_REMOVE | If this value is specified along with DDD_REMOVE_DEFINITION, the function will use an exact match to determine which mapping to remove. Use this value to insure that you do not delete something that you did not define.

lpDeviceName
[in] Pointer to an MS-DOS device name string specifying the device the function is defining, redefining, or deleting. The device name string must not have a trailing colon, unless a drive letter (C or D, for example) is being defined, redefined, or deleted. In no case is a trailing backslash allowed.
lpTargetPath
[in] Pointer to a path string that will implement this device. The string is an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string.

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

MS-DOS device names are stored as symbolic links in the object name space. The code that converts an MS-DOS path into a corresponding path uses these symbolic links to map MS-DOS devices and drive letters. The DefineDosDevice function provides a mechanism whereby an application can modify the symbolic links used to implement the MS-DOS device name space.

To retrieve the current mapping for a particular MS-DOS device name or to obtain a list of all MS-DOS devices known to the system, use the QueryDosDevice function.

MS-DOS Device names are global. After it is defined, an MS-DOS device name remains visible to all processes until either it is explicitly removed or the system restarts.

Windows 2000 or later: To define a drive letter assignment that is persistent across boots and not a network share, use the SetVolumeMountPoint function. If the volume to be mounted already has a drive letter assigned to it, use the DeleteVolumeMountPoint function to remove the assignment.

Note Drive letters and device names defined at system boot time are protected from redefinition and deletion unless the user is an administrator.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File I/O Overview, File I/O Functions, DeleteVolumeMountPoint , QueryDosDevice, SetVolumeMountPoint


DeleteFile

The DeleteFile function deletes an existing file.

BOOL DeleteFile(
  LPCTSTR lpFileName   // file name
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the file to be deleted.

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

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

If an application attempts to delete a file that does not exist, the DeleteFile function fails.

To delete or rename a file, you must have either delete permission on the file or delete child permission in the parent directory. If you set up a directory with all access except delete and delete child and the ACLs of new files are inherited, then you should be able to create a file without being able to delete it. However, you can then create a file, and you will get all the access you request on the handle returned to you at the time you create the file. If you requested delete permission at the time you created the file, you could delete or rename the file with that handle but not with any other.

Windows 95/98/Me: The DeleteFile function deletes a file even if it is open for normal I/O or as a memory-mapped file. To prevent loss of data, close files before attempting to delete them.

Windows NT/2000 or later: The DeleteFile function fails if an application attempts to delete a file that is open for normal I/O or as a memory-mapped file.

To close an open file, use the CloseHandle function.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Creating and Opening Files.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CloseHandle, CreateFile


FileIOCompletionRoutine

The FileIOCompletionRoutine function is an application-defined callback function used with the ReadFileEx and WriteFileEx functions. It is called when the asynchronous input and output (I/O) operation is completed or canceled and the calling thread is in an alertable state (using the SleepEx, MsgWaitForMultipleObjectsEx, WaitForSingleObjectEx, or WaitForMultipleObjectsEx function with the fAlertable flag set to TRUE).

The LPOVERLAPPED_COMPLETION_ROUTINE type defines a pointer to this callback function. FileIOCompletionRoutine is a placeholder for the application-defined function name.

VOID CALLBACK FileIOCompletionRoutine(
  DWORD dwErrorCode,                // completion code
  DWORD dwNumberOfBytesTransfered,  // number of bytes transferred
  LPOVERLAPPED lpOverlapped         // I/O information buffer
);

Parameters

dwErrorCode
[in] Specifies the I/O completion status. This parameter can be one of the following values.
Value | Meaning
0 | The I/O was successful.
ERROR_HANDLE_EOF | The ReadFileEx function tried to read past the end of the file.

dwNumberOfBytesTransfered
[in] Specifies the number of bytes transferred. If an error occurs, this parameter is zero.
lpOverlapped
[in] Pointer to the OVERLAPPED structure specified by the asynchronous I/O function.

The system does not use the hEvent member of the OVERLAPPED structure; the calling application may use this member to pass information to the completion routine. The system does not use the OVERLAPPED structure after the completion routine is called, so the completion routine can deallocate the memory used by the overlapped structure.

Return Values

This function does not return a value.

Remarks

The FileIOCompletionRoutine function is a placeholder for an application-defined or library-defined function name.

Returning from this function allows another pending I/O completion routine to be called. All waiting completion routines are called before the alertable thread's wait is completed with a return code of WAIT_IO_COMPLETION. The system may call the waiting completion routines in any order. They may or may not be called in the order the I/O functions are completed.

Each time the system calls a completion routine, it uses some of the application's stack. If the completion routine does additional asynchronous I/O and alertable waits, the stack may grow.

For more information, see Asynchronous Procedure Calls.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Functions, OVERLAPPED, ReadFileEx, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFileEx


FindClose

The FindClose function closes the specified search handle. The FindFirstFile and FindNextFile functions use the search handle to locate files with names that match a given name.

BOOL FindClose(
  HANDLE hFindFile   // file search handle
);

Parameters

hFindFile
[in/out] File search handle. This handle must have been previously opened by the FindFirstFile function.

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

After the FindClose function is called, the handle specified by the hFindFile parameter cannot be used in subsequent calls to either the FindNextFile or FindClose function.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, FindFirstFile, FindNextFile


FindCloseChangeNotification

The FindCloseChangeNotification function stops change notification handle monitoring.

BOOL FindCloseChangeNotification(
  HANDLE hChangeHandle   // handle to change notification
);

Parameters

hChangeHandle
[in] Handle to a change notification handle created by the FindFirstChangeNotification function.

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

After the FindCloseChangeNotification function is called, the handle specified by the hChangeHandle parameter cannot be used in subsequent calls to either the FindNextChangeNotification or FindCloseChangeNotification function.

Change notifications can also be used in the wait functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, FindFirstChangeNotification, FindNextChangeNotification


FindFirstChangeNotification

The FindFirstChangeNotification function creates a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle succeeds when a change matching the filter conditions occurs in the specified directory or subtree.

HANDLE FindFirstChangeNotification(
  LPCTSTR lpPathName,    // directory name
  BOOL bWatchSubtree,    // monitoring option
  DWORD dwNotifyFilter   // filter conditions
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the path of the directory to watch.

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

bWatchSubtree
[in] Specifies whether the function will monitor the directory or the directory tree. If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it monitors only the specified directory.
dwNotifyFilter
[in] Specifies the filter conditions that satisfy a change notification wait. This parameter can be one or more of the following values.
Value | Meaning
FILE_NOTIFY_CHANGE_FILE_NAME | Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes include renaming, creating, or deleting a file name.
FILE_NOTIFY_CHANGE_DIR_NAME | Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes include creating or deleting a directory.
FILE_NOTIFY_CHANGE_ATTRIBUTES | Any attribute change in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SIZE | Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_WRITE | Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_SECURITY | Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.

Return Values

If the function succeeds, the return value is a handle to a find change notification object.

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

Remarks

The wait functions can monitor the specified directory or subtree by using the handle returned by the FindFirstChangeNotification function. A wait is satisfied when one of the filter conditions occurs in the monitored directory or subtree.

After the wait has been satisfied, the application can respond to this condition and continue monitoring the directory by calling the FindNextChangeNotification function and the appropriate wait function. When the handle is no longer needed, it can be closed by using the FindCloseChangeNotification function.

For example, see Monitoring Changes in a Directory or Directory Tree.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, FindCloseChangeNotification, FindNextChangeNotification


FindFirstFile

The FindFirstFile function searches a directory for a file whose name matches the specified file name. FindFirstFile examines subdirectory names as well as file names.

To specify additional attributes to be used in the search, use the FindFirstFileEx function.

HANDLE FindFirstFile(
  LPCTSTR lpFileName,               // file name
  LPWIN32_FIND_DATA lpFindFileData  // data buffer
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies a valid directory or path and file name, which can contain wildcard characters (* and ?). If the string ends with a wildcard, a period, or a directory name, the user must have access to the root and all subdirectories on the path.

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

lpFindFileData
[out] Pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory.

Return Values

If the function succeeds, the return value is a search handle used in a subsequent call to FindNextFile or FindClose.

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

Remarks

The FindFirstFile function opens a search handle and returns information about the first file whose name matches the specified pattern. After the search handle has been established, use the FindNextFile function to search for other files that match the same pattern. When the search handle is no longer needed, close it by using the FindClose function.

In rare cases, file attribute information on NTFS file systems may not be current at the time you call this function. To obtain the current NTFS file attributes, call GetFileInformationByHandle.

This function searches for files by name only; it cannot be used for attribute-based searches.

You cannot use root directories as the lpFileName input string for FindFirstFile, with or without a trailing backslash. To examine files in a root directory, use something like "C:\*" and step through the directory with FindNextFile. To get the attributes of a root directory, use GetFileAttributes. Prepending the string "\\?\" does not allow access to the root directory.

Similarly, on network shares, you can use an lpFileName of the form "\\server\service\*" but you cannot use an lpFileName that points to the share itself, such as "\\server\service".

To examine any directory other than a root directory, use an appropriate path to that directory, with no trailing backslash. For example, an argument of "C:\windows" will return information about the directory "C:\windows", not about any directory or file in "C:\windows". An attempt to open a search with a trailing backslash will always fail.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

The following code shows a minimal use of FindFirstFile.

#define _WIN32_WINNT 0x0400

#include "windows.h"

int
main(int argc, char *argv[])
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;

  printf ("Target file is %s.\n", argv[1]);

  hFind = FindFirstFile(argv[1], &FindFileData);

  if (hFind == INVALID_HANDLE_VALUE) {
    printf ("Invalid File Handle. Get Last Error reports %d\n", GetLastError ());
  } else {
    printf ("The first file found is %s\n", FindFileData.cFileName);
    FindClose(hFind);
  }

  return (0);
}

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, FindClose, FindFirstFileEx, FindNextFile, GetFileAttributes, SetFileAttributes, WIN32_FIND_DATA


FindFirstFileEx

The FindFirstFileEx function searches a directory for a file whose name and attributes match those specified in the function call.

HANDLE FindFirstFileEx(
  LPCTSTR lpFileName,              // file name
  FINDEX_INFO_LEVELS fInfoLevelId, // information level
  LPVOID lpFindFileData,           // information buffer
  FINDEX_SEARCH_OPS fSearchOp,     // filtering type
  LPVOID lpSearchFilter,           // search criteria
  DWORD dwAdditionalFlags          // reserved
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies a valid directory or path and file name, which can contain wildcard characters (* and ?). If the string ends with a wildcard, a period, or a directory name, the user must have access to the root and all subdirectories on the path.

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.

fInfoLevelId
[in] Specifies a FINDEX_INFO_LEVELS enumeration type that gives the information level of the returned data.
lpFindFileData
[out] Pointer to the buffer that receives the file data. The pointer type is determined by the level of information specified in the fInfoLevelId parameter.
fSearchOp
[in] Specifies a FINDEX_SEARCH_OPS enumeration type that gives the type of filtering to perform beyond wildcard matching.
lpSearchFilter
[in] If the specified fSearchOp needs structured search information, lpSearchFilter points to the search criteria. At this time, none of the supported fSearchOp values require extended search information. Therefore, this pointer must be NULL.
dwAdditionalFlags
Reserved for future use. This parameter must be zero.

Return Values

If the function succeeds, the return value is a search handle that can be used in a subsequent call to the FindNextFile or FindClose functions.

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

Remarks

The FindFirstFileEx function is provided to open a search handle and return information about the first file whose name matches the specified pattern and attributes.

In rare cases, file attribute information on NTFS file systems may not be current at the time you call this function. To obtain the current NTFS file attributes, call GetFileInformationByHandle.

If the underlying file system does not support the specified type of filtering, other than directory filtering, FindFirstFileEx fails with the error ERROR_NOT_SUPPORTED. The application has to use FINDEX_SEARCH_OPS type FileExSearchNameMatch and perform its own filtering.

After the search handle has been established, use it in the FindNextFile function to search for other files that match the same pattern with the same filtering being performed. When the search handle is no longer needed, it should be closed using the FindClose function.

You cannot use root directories as the lpFileName input string for FindFirstFileEx, with or without a trailing backslash. To examine files in a root directory, use something like "C:\*" and step through the directory with FindNextFile. To get the attributes of a root directory, use GetFileAttributes. Prepending the string "\\?\" does not allow access to the root directory.

Similarly, on network shares, you can use an lpFileName of the form "\\server\service\*" but you cannot use an lpFileName that points to the share itself, such as "\\server\service".

To examine any directory other than a root directory, use an appropriate path to that directory, with no trailing backslash. For example, an argument of "C:\windows" will return information about the directory "C:\windows", not about any directory or file in "C:\windows". An attempt to open a search with a trailing backslash will always fail.

The call

FindFirstFileEx( lpFileName,
                 FindExInfoStandard,
                 lpFindData,
                 FindExSearchNameMatch,
                 NULL,
                 0 );

is equivalent to the call

FindFirstFile( lpFileName, lpFindData);

Examples

The following code shows a minimal use of FindFirstFileEx. This program is the equivalent of the example shown in FindFirstFile.

#define _WIN32_WINNT 0x0400

#include "windows.h"

int
main(int argc, char *argv[])
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;

  printf ("Target file is %s.\n", argv[1]);

  hFind = FindFirstFileEx(argv[1], FindExInfoStandard, &FindFileData,
                 FindExSearchNameMatch, NULL, 0 );

  if (hFind == INVALID_HANDLE_VALUE) {
    printf ("Invalid File Handle. Get Last Error reports %d\n", GetLastError ());
  } else {
    printf ("The first file found is %s\n", FindFileData.cFileName);
    FindClose(hFind);
  }

  return (0);
}

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File I/O Overview, File I/O Functions, FINDEX_INFO_LEVELS, FINDEX_SEARCH_OPS, FindFirstFile, FindNextFile, FindClose, GetFileAttributes


FindNextChangeNotification

The FindNextChangeNotification function requests that the operating system signal a change notification handle the next time it detects an appropriate change.

BOOL FindNextChangeNotification(
  HANDLE hChangeHandle   // handle to change notification
);

Parameters

hChangeHandle
[in] Handle to a change notification handle created by the FindFirstChangeNotification function.

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

After the FindNextChangeNotification function returns successfully, the application can wait for notification that a change has occurred by using the wait functions.

If a change occurs after a call to FindFirstChangeNotification but before a call to FindNextChangeNotification, the operating system records the change. When FindNextChangeNotification is executed, the recorded change immediately satisfies a wait for the change notification.

FindNextChangeNotification should not be used more than once on the same handle without using one of the wait functions. An application may miss a change notification if it uses FindNextChangeNotification when there is a change request outstanding.

When hChangeHandle is no longer needed, close it by using the FindCloseChangeNotification function.

For example, see Monitoring Changes in a Directory or Directory Tree.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, FindCloseChangeNotification, FindFirstChangeNotification


FindNextFile

The FindNextFile function continues a file search from a previous call to the FindFirstFile function.

BOOL FindNextFile(
  HANDLE hFindFile,                // search handle
  LPWIN32_FIND_DATA lpFindFileData // data buffer
);

Parameters

hFindFile
[in] Search handle returned by a previous call to the FindFirstFile function.
lpFindFileData
[out] Pointer to the WIN32_FIND_DATA structure that receives information about the found file or subdirectory. The structure can be used in subsequent calls to FindNextFile to refer to the found file or directory.

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. If no matching files can be found, the GetLastError function returns ERROR_NO_MORE_FILES.

Remarks

The FindNextFile function searches for files by name only; it cannot be used for attribute-based searches.

In rare cases, file attribute information on NTFS file systems may not be current at the time you call this function. To be assured of getting the current NTFS file attributes, call GetFileInformationByHandle.

The order in which this function returns the file names is dependent on the file system type. With NTFS and CDFS file systems, the names are returned in alphabetical order. With FAT file systems, the names are returned in the order the files were written to the disk, which may or may not be in alphabetical order.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, FindClose, FindFirstFile, GetFileAttributes, SetFileAttributes, WIN32_FIND_DATA


FlushFileBuffers

The FlushFileBuffers function clears the buffers for the specified file and causes all buffered data to be written to the file.

BOOL FlushFileBuffers(
  HANDLE hFile  // handle to file
);

Parameters

hFile
[in] Handle to an open file. The function flushes this file's buffers. The file handle must have GENERIC_WRITE access to the file.

If hFile is a handle to a communications device, the function only flushes the transmit buffer.

If hFile is a handle to the server end of a named pipe, the function does not return until the client has read all buffered data from the pipe.

Windows NT/2000 or later: The function fails if hFile is a handle to console output. That is because console output is not buffered. The function returns FALSE, and GetLastError returns ERROR_INVALID_HANDLE.

Windows 95/98/Me: The function does nothing if hFile is a handle to console output. That is because console output is not buffered. The function returns TRUE, but it does nothing.

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

The WriteFile and WriteFileEx functions typically write data to an internal buffer that the operating system writes to disk on a regular basis. The FlushFileBuffers function writes all of the buffered information for the specified file to disk.

You can pass the same file handle used with the _lread, _lwrite, _lcreat, and related functions to FlushFileBuffers.

For example, see Multithreaded Pipe Server.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, _lread, _lwrite, _lcreat, WriteFile, WriteFileEx


GetBinaryType

The GetBinaryType function determines whether a file is executable, and if so, what type of executable file it is. That last property determines which subsystem an executable file runs under.

BOOL GetBinaryType (
  LPCTSTR lpApplicationName,  // full file path
  LPDWORD lpBinaryType        // binary type information
);

Parameters

lpApplicationName
[in] Pointer to a null-terminated string that contains the full path of the file whose binary type the function shall determine.

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.

lpBinaryType
[out] Pointer to a variable to receive information about the executable type of the file specified by lpApplicationName. The function adjusts a set of bit flags in this variable. The following bit flag constants are defined.
Value | Description
SCS_32BIT_BINARY | A 32-bit Windows-based application
SCS_64BIT_BINARY | Whistler: A 64-bit Windows-based application.
SCS_DOS_BINARY | An MS-DOS – based application
SCS_OS216_BINARY | A 16-bit OS/2-based application
SCS_PIF_BINARY | A PIF file that executes an MS-DOS – based application
SCS_POSIX_BINARY | A POSIX – based application
SCS_WOW_BINARY | A 16-bit Windows-based application

Return Values

If the file is executable, the return value is nonzero. The function sets the variable pointed to by lpBinaryType to indicate the file's executable type.

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

Remarks

As an alternative, you can obtain the same information by calling the SHGetFileInfo function, passing the SHGFI_EXETYPE flag in the uFlags parameter.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File I/O Overview, File I/O Functions


GetCurrentDirectory

The GetCurrentDirectory function retrieves the current directory for the current process.

DWORD GetCurrentDirectory(
  DWORD nBufferLength,  // size of directory buffer
  LPTSTR lpBuffer       // directory buffer
);

Parameters

nBufferLength
[in] Specifies the length, in TCHARs, of the buffer for the current directory string. The buffer length must include room for a terminating null character.
lpBuffer
[out] Pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory.

Return Values

If the function succeeds, the return value specifies the number of characters written to the buffer, not including the terminating null character.

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

If the buffer pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, including the number of bytes necessary for a terminating null character.

For an example, see Creating a Directory Listing in a Single Selection List Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CreateDirectory, GetSystemDirectory, GetWindowsDirectory, RemoveDirectory, SetCurrentDirectory


GetDiskFreeSpace

The GetDiskFreeSpace function retrieves information about the specified disk, including the amount of free space on the disk.

The GetDiskFreeSpace function cannot report volume sizes that are greater than 2 GB. To ensure that your application works with large capacity hard drives, use the GetDiskFreeSpaceEx function.

BOOL GetDiskFreeSpace(
  LPCTSTR lpRootPathName,          // root path
  LPDWORD lpSectorsPerCluster,     // sectors per cluster
  LPDWORD lpBytesPerSector,        // bytes per sector
  LPDWORD lpNumberOfFreeClusters,  // free clusters
  LPDWORD lpTotalNumberOfClusters  // total clusters
);

Parameters

lpRootPathName
[in] Pointer to a null-terminated string that specifies the root directory of the disk to return information about. If lpRootPathName is NULL, the function uses the root of the current directory. If this parameter is a UNC name, you must follow it with a trailing backslash. For example, you would specify \\MyServer\MyShare as \\MyServer\MyShare\. However, a drive specification such as "C:" must have a trailing backslash.

Windows 95: The initial release of Windows 95 does not support UNC paths for the lpszRootPathName parameter. To query the free disk space using a UNC path, temporarily map the UNC path to a drive letter, query the free disk space on the drive, then remove the temporary mapping.

Windows 95 OSR2 and later: UNC paths are supported.

lpSectorsPerCluster
[out] Pointer to a variable for the number of sectors per cluster.
lpBytesPerSector
[out] Pointer to a variable for the number of bytes per sector.
lpNumberOfFreeClusters
[out] Pointer to a variable for the total number of free clusters on the disk that are available to the user associated with the calling thread.

Windows 2000 and later: If per-user disk quotas are in use, this value may be less than the total number of free clusters on the disk.

lpTotalNumberOfClusters
[out] Pointer to a variable for the total number of clusters on the disk that are available to the user associated with the calling thread.

Windows 2000 and later: If per-user disk quotas are in use, this value may be less than the total number of clusters on the disk.

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

The GetDiskFreeSpaceEx function lets you avoid some of the arithmetic required by the GetDiskFreeSpace function.

Windows 95 OSR2 and later: The GetDiskFreeSpaceEx function is available beginning with Windows 95 OEM Service Release 2 (OSR2), and you should use it whenever possible. The GetDiskFreeSpaceEx function returns correct values for all volumes, including those that are larger than 2 gigabytes.

Windows 95: For volumes that are larger than 2 gigabytes, the GetDiskFreeSpace function may return misleading values. The function caps the values stored into *lpNumberOfFreeClusters and *lpTotalNumberOfClusters so as to never report volume sizes that are greater than 2 gigabytes. Even on volumes that are smaller than 2 gigabytes, the values stored into *lpSectorsPerCluster, *lpNumberOfFreeClusters, and *lpTotalNumberOfClusters values may be incorrect. That is because the operating system manipulates the values so that computations with them yield the correct volume size.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetDiskFreeSpaceEx, GetDriveType


GetDiskFreeSpaceEx

The GetDiskFreeSpaceEx function retrieves information about the amount of space available on a disk volume: the total amount of space, the total amount of free space, and the total amount of free space available to the user associated with the calling thread.

BOOL GetDiskFreeSpaceEx(
  LPCTSTR lpDirectoryName,                 // directory name
  PULARGE_INTEGER lpFreeBytesAvailable,    // bytes available to caller
  PULARGE_INTEGER lpTotalNumberOfBytes,    // bytes on disk
  PULARGE_INTEGER lpTotalNumberOfFreeBytes // free bytes on disk
);

Parameters

lpDirectoryName
[in] Pointer to a null-terminated string that specifies a directory on the disk of interest. This string can be a UNC name. If this parameter is a UNC name, you must follow it with an additional backslash. For example, you would specify \\MyServer\MyShare as \\MyServer\MyShare\.

If lpDirectoryName is NULL, the GetDiskFreeSpaceEx function retrieves information about the disk that contains the current directory.

Note that lpDirectoryName does not have to specify the root directory on a disk. The function accepts any directory on the disk.

lpFreeBytesAvailable
[out] Pointer to a variable that receives the total number of free bytes on the disk that are available to the user associated with the calling thread.

Windows 2000 and later: If per-user quotas are in use, this value may be less than the total number of free bytes on the disk.

lpTotalNumberOfBytes
[out] Pointer to a variable that receives the total number of bytes on the disk that are available to the user associated with the calling thread.

Windows 2000 and later: If per-user quotas are in use, this value may be less than the total number of bytes on the disk.

lpTotalNumberOfFreeBytes
[out] Pointer to a variable that receives the total number of free bytes on the disk.

This parameter can be NULL.

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 values obtained by this function are of type ULARGE_INTEGER. Be careful not to truncate these values to 32 bits.

Windows 95 OSR2 and later: The GetDiskFreeSpaceEx function is available beginning with Windows 95 OEM Service Release 2 (OSR2). To determine whether GetDiskFreeSpaceEx is available, call GetModuleHandle to get the handle to Kernel32.dll. Then you can call GetProcAddress.

The following code fragment shows one way to do this:

pGetDiskFreeSpaceEx = GetProcAddress( GetModuleHandle("kernel32.dll"),
                         "GetDiskFreeSpaceExA");

if (pGetDiskFreeSpaceEx)
{
   fResult = pGetDiskFreeSpaceEx (pszDrive,
                (PULARGE_INTEGER)&i64FreeBytesToCaller,
                (PULARGE_INTEGER)&i64TotalBytes,
                (PULARGE_INTEGER)&i64FreeBytes);

// Process GetDiskFreeSpaceEx results.
}

else
{
   fResult = GetDiskFreeSpace (pszDrive,
                &dwSectPerClust,
                &dwBytesPerSect,
                &dwFreeClusters,
                &dwTotalClusters)

// Process GetDiskFreeSpace results.

}

It is not necessary to call LoadLibrary on Kernel32.dll because it is already loaded into every process address space.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 OSR2 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.

See Also

File I/O Overview, File I/O Functions, GetDiskFreeSpace, GetModuleHandle, GetProcAddress


GetDriveType

The GetDriveType function determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive.

UINT GetDriveType(
  LPCTSTR lpRootPathName   // root directory
);

Parameters

lpRootPathName
[in] Pointer to a null-terminated string that specifies the root directory of the disk to return information about. A trailing backslash is required. If lpRootPathName is NULL, the function uses the root of the current directory.

Return Values

The return value specifies the type of drive. It can be one of the following values.

Value | Meaning
DRIVE_UNKNOWN | The drive type cannot be determined.
DRIVE_NO_ROOT_DIR | The root path is invalid. For example, no volume is mounted at the path.
DRIVE_REMOVABLE | The disk can be removed from the drive.
DRIVE_FIXED | The disk cannot be removed from the drive.
DRIVE_REMOTE | The drive is a remote (network) drive.
DRIVE_CDROM | The drive is a CD-ROM drive.
DRIVE_RAMDISK | The drive is a RAM disk.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetDiskFreeSpace


GetFileAttributes

The GetFileAttributes function retrieves attributes for a specified file or directory.

This function retrieves a set of FAT-style attribute information. The GetFileAttributesEx function can obtain other sets of file or directory attribute information.

DWORD GetFileAttributes(
  LPCTSTR lpFileName   // name of file or directory
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the name of a file or directory.

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

Return Values

If the function succeeds, the return value contains the attributes of the specified file or directory.

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

The attributes can be one or more of the following values.

Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file or directory is an archive file or directory. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED | The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DEVICE | Reserved; do not use.
FILE_ATTRIBUTE_DIRECTORY | The handle identifies a directory.
FILE_ATTRIBUTE_ENCRYPTED | The file or directory is encrypted. For a file, this means that all data streams in the file are encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_HIDDEN | The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL | The file or directory 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 or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_REPARSE_POINT | The file has an associated reparse point.
FILE_ATTRIBUTE_SPARSE_FILE | The file is a sparse file.
FILE_ATTRIBUTE_SYSTEM | The file or directory 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.

Remarks

When GetFileAttributes is called on a directory containing a volume mount point, the file attributes returned are those of the directory where the volume mount point is set, not those of the root directory in the target mounted volume. To obtain the file attributes of the mounted volume, call GetVolumeNameForVolumeMountPoint to obtain the name of the target volume. Then use the resulting name in a call to GetFileAttributes. The results will be the attributes of the root directory on the target volume.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, DeviceIoControl, FindFirstFile, FindNextFile, GetFileAttributesEx, SetFileAttributes


GetFileAttributesEx

The GetFileAttributesEx function retrieves attributes for a specified file or directory.

BOOL GetFileAttributesEx(
  LPCTSTR lpFileName,                   // file or directory name
  GET_FILEEX_INFO_LEVELS fInfoLevelId,  // attribute
  LPVOID lpFileInformation              // attribute information
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies a file or directory.

Windows NT/2000 or later: 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 98 and later: This string must not exceed MAX_PATH characters.

fInfoLevelId
[in] Specifies a GET_FILEEX_INFO_LEVELS enumeration type that gives the set of attribute information to obtain.
lpFileInformation
[out] Pointer to a buffer that receives the attribute information. The type of attribute information stored into this buffer is determined by the value of fInfoLevelId.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

The GetFileAttributes function retrieves a set of FAT-style attribute information. GetFileAttributesEx can obtain other sets of file or directory attribute information. Currently, GetFileAttributeEx retrieves a set of standard attributes that is a superset of the FAT-style attribute information.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 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.

See Also

File I/O Overview, File I/O Functions, GetFileAttributes, GET_FILEEX_INFO_LEVELS, SetFileAttributes


GetFileInformationByHandle

The GetFileInformationByHandle function retrieves file information for a specified file.

BOOL GetFileInformationByHandle(
  HANDLE hFile,                                  // handle to file
  LPBY_HANDLE_FILE_INFORMATION lpFileInformation // buffer
);

Parameters

hFile
[in] Handle to the file for which to obtain information.

This handle should not be a pipe handle. The GetFileInformationByHandle function does not work with pipe handles.

lpFileInformation
[out] Pointer to a BY_HANDLE_FILE_INFORMATION structure that receives the file information. The structure can be used in subsequent calls to GetFileInformationByHandle to refer to the information about the file.

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

Depending on the underlying network components of the operating system and the type of server connected to, the GetFileInformationByHandle function may fail, return partial information, or full information for the given file. In general, you should not use GetFileInformationByHandle unless your application is intended to be run on a limited set of operating system configurations.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, BY_HANDLE_FILE_INFORMATION


GetFileSize

The GetFileSize function retrieves the size of a specified file.

This function stores the file size in a DWORD value. To retrieve a file size that is larger than a DWORD value, use the GetFileSizeEx function.

DWORD GetFileSize(
  HANDLE hFile,           // handle to file
  LPDWORD lpFileSizeHigh  // high-order word of file size
);

Parameters

hFile
[in] Handle to the file whose size is to be returned. This handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.
lpFileSizeHigh
[out] Pointer to the variable where the high-order word of the file size is returned. This parameter can be NULL if the application does not require the high-order word.

Return Values

If the function succeeds, the return value is the low-order doubleword of the file size, and, if lpFileSizeHigh is non-NULL, the function puts the high-order doubleword of the file size into the variable pointed to by that parameter.

If the function fails and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call GetLastError.

If the function fails and lpFileSizeHigh is non-NULL, the return value is INVALID_FILE_SIZE and GetLastError will return a value other than NO_ERROR.

Remarks

You cannot use the GetFileSize function with a handle of a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

The GetFileSize function retrieves the uncompressed size of a file. Use the GetCompressedFileSize function to obtain the compressed size of a file.

Note that if the return value is INVALID_FILE_SIZE and lpFileSizeHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded or failed. The following sample code illustrates this point:

// Case One: calling the function with
//           lpFileSizeHigh == NULL

// Try to obtain hFile's size
dwSize = GetFileSize (hFile, NULL) ;

// If we failed ...
if (dwSize == INVALID_FILE_SIZE)
{
    // Obtain the error code.
    dwError = GetLastError() ;

    // Deal with that failure.
    .
    .
    .

    } // End of error handler

//
// Case Two: calling the function with
//           lpFileSizeHigh != NULL

// Try to obtain hFile's huge size.
dwSizeLow = GetFileSize (hFile, & dwSizeHigh) ;

// If we failed ...
if (dwSizeLow == INVALID_FILE_SIZE
    &&
    (dwError = GetLastError()) != NO_ERROR )
{
    // Deal with that failure.
    .
    .
    .

    } // End of error handler.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Two Examples of File Mapping.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, GetCompressedFileSize, GetFileSizeEx, GetFileType


GetFileSizeEx

The GetFileSizeEx function retrieves the size of a specified file.

BOOL GetFileSizeEx(
  HANDLE hFile,              // handle to file
  PLARGE_INTEGER lpFileSize  // file size
);

Parameters

hFile
[in] Handle to the file whose size is to be returned. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.
lpFileSize
[out] Pointer to a LARGE_INTEGER structure that receives the file size.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, LARGE_INTEGER


GetFileType

The GetFileType function retrieves the file type for the specified file.

DWORD GetFileType(
  HANDLE hFile   // handle to file
);

Parameters

hFile
[in] Handle to an open file.

Return Values

The return value is one of the following values.

Value | Meaning
FILE_TYPE_UNKNOWN | The type of the specified file is unknown.
FILE_TYPE_DISK | The specified file is a disk file.
FILE_TYPE_CHAR | The specified file is a character file, typically an LPT device or a console.
FILE_TYPE_PIPE | The specified file is either a named or anonymous pipe.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, GetFileSize, GetFileTime


GetFullPathName

The GetFullPathName function retrieves the full path and file name of a specified file.

DWORD GetFullPathName(
  LPCTSTR lpFileName,  // file name
  DWORD nBufferLength, // size of path buffer
  LPTSTR lpBuffer,     // path buffer
  LPTSTR *lpFilePart   // address of file name in path
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies a valid file name. This string can use either short (the 8.3 form) or long file names.
nBufferLength
[in] Specifies the size, in TCHARs, of the buffer for the drive and path.
lpBuffer
[out] Pointer to a buffer that receives the null-terminated string for the name of the drive and path.
lpFilePart
[out] Pointer to a buffer that receives the address (in lpBuffer) of the final file name component in the path.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the terminating null character.

If the lpBuffer buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, required to hold the path. Therefore, if the return value is greater than nBufferLength, call the function again with a buffer that is large enough to hold the path.

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

Remarks

GetFullPathName merges the name of the current drive and directory with the specified file name to determine the full path and file name of the specified file. It also calculates the address of the file name portion of the full path and file name. This function does not verify that the resulting path and file name are valid or that they refer to an existing file on the associated volume.

GetFullPathName does no conversion of the specified file name, lpFileName. If the specified file name exists, you can use GetLongPathName and GetShortPathName to convert to long and short path names, respectively.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetLongPathName, GetShortPathName, GetTempPath, SearchPath


GetLogicalDrives

The GetLogicalDrives function retrieves a bitmask representing the currently available disk drives.

DWORD GetLogicalDrives(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is a bitmask representing the currently available disk drives. Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, GetLogicalDriveStrings


GetLogicalDriveStrings

The GetLogicalDriveStrings function fills a buffer with strings that specify valid drives in the system.

DWORD GetLogicalDriveStrings(
  DWORD nBufferLength,  // size of buffer
  LPTSTR lpBuffer       // drive strings buffer
);

Parameters

nBufferLength
[in] Specifies the maximum size, in characters, of the buffer pointed to by lpBuffer. This size does not include the terminating null character.
lpBuffer
[out] Pointer to a buffer that receives a series of null-terminated strings, one for each valid drive in the system, that end with a second null character. The following example shows the buffer contents with <null> representing the terminating null character.
c:\<null>d:\<null><null>

Return Values

If the function succeeds, the return value is the length, in characters, of the strings copied to the buffer, not including the terminating null character. Note that an ANSI-ASCII null character uses one byte, but a Unicode null character uses two bytes.

If the buffer is not large enough, the return value is greater than nBufferLength. It is the size of the buffer required to hold the drive strings.

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

Remarks

Each string in the buffer may be used wherever a root directory is required, such as for the GetDriveType and GetDiskFreeSpace functions.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetDriveType, GetDiskFreeSpace, GetLogicalDrives


GetLongPathName

The GetLongPathName function converts the specified path to its long form. If no long path is found, this function simply returns the specified name.

DWORD GetLongPathName(
  LPCTSTR lpszShortPath, // file name
  LPTSTR lpszLongPath,   // path buffer
  DWORD cchBuffer        // size of path buffer
);

Parameters

lpszShortPath
[in] Pointer to a null-terminated path to be converted.

Windows 2000 and later: 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 98 and later: This string must not exceed MAX_PATH characters.

lpszLongPath
[out] Pointer to the buffer to receive the long path. You can use the same buffer you used for the lpszShortPath parameter.
cchBuffer
[in] Specifies the size of the buffer, in TCHARs.

Return Values

If the function succeeds, the return value is the length of the string copied to the lpszLongPath parameter, in TCHARs. This length does not include the terminating null character.

If the lpszLongPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, required to hold the path. Therefore, if the return value is greater than cchBuffer, call the function again with a buffer that is large enough to hold the path.

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

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File I/O Overview, File I/O Functions, GetFullPathName, GetShortPathName


GetQueuedCompletionStatus

The GetQueuedCompletionStatus function attempts to dequeue an I/O completion packet from a specified I/O completion port. If there is no completion packet queued, the function waits for a pending I/O operation associated with the completion port to complete.

BOOL GetQueuedCompletionStatus(
  HANDLE CompletionPort,       // handle to completion port
  LPDWORD lpNumberOfBytes,     // bytes transferred
  PULONG_PTR lpCompletionKey,  // file completion key
  LPOVERLAPPED *lpOverlapped,  // buffer
  DWORD dwMilliseconds         // optional timeout value
);

Parameters

CompletionPort
[in] Handle to the completion port of interest. To create a completion port, use the CreateIoCompletionPort function.
lpNumberOfBytes
[out] Pointer to a variable that receives the number of bytes transferred during an I/O operation that has completed.
lpCompletionKey
[out] Pointer to a variable that receives the completion key value associated with the file handle whose I/O operation has completed. A completion key is a per-file key that is specified in a call to CreateIoCompletionPort.
lpOverlapped
[out] Pointer to a variable that receives the address of the OVERLAPPED structure that was specified when the completed I/O operation was started.

The following functions can be used to start I/O operations that complete using completion ports. You must pass the function an OVERLAPPED structure and a file handle associated with an completion port (by a call to CreateIoCompletionPort) to invoke the I/O completion port mechanism:

  • ConnectNamedPipe
  • DeviceIoControl
  • LockFileEx
  • ReadDirectoryChangesW
  • ReadFile
  • TransactNamedPipe
  • WaitCommEvent
  • WriteFile

Even if you have passed the function a file handle associated with a completion port and a valid OVERLAPPED structure, an application can prevent completion port notification. This is done by specifying a valid event handle for the hEvent member of the OVERLAPPED structure, and setting its low-order bit. A valid event handle whose low-order bit is set keeps I/O completion from being queued to the completion port.

dwMilliseconds
[in] Specifies the number of milliseconds that the caller is willing to wait for an completion packet to appear at the completion port. If a completion packet doesn't appear within the specified time, the function times out, returns FALSE, and sets *lpOverlapped to NULL.

If dwMilliseconds is INFINITE, the function will never time out. If dwMilliseconds is zero and there is no I/O operation to dequeue, the function will time out immediately.

Return Values

If the function dequeues a completion packet for a successful I/O operation from the completion port, the return value is nonzero. The function stores information in the variables pointed to by the lpNumberOfBytesTransferred, lpCompletionKey, and lpOverlapped parameters.

If *lpOverlapped is NULL and the function does not dequeue a completion packet from the completion port, the return value is zero. The function does not store information in the variables pointed to by the lpNumberOfBytesTransferred and lpCompletionKey parameters. To get extended error information, call GetLastError. If the function did not dequeue a completion packet because the wait timed out, GetLastError returns WAIT_TIMEOUT.

If *lpOverlapped is not NULL and the function dequeues a completion packet for a failed I/O operation from the completion port, the return value is zero. The function stores information in the variables pointed to by lpNumberOfBytesTransferred, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.

Remarks

This function associates a thread with the specified completion port. A thread can be associated with at most one completion port.

The I/O system can be instructed to send completion notification packets to completion ports, where they are queued. The CreateIoCompletionPort function provides a mechanism for this.

When you perform an input/output operation with a file handle that has an associated input/output completion port, the I/O system sends a completion notification packet to the completion port when the I/O operation completes. The completion port places the completion packet in a first-in-first-out queue. The GetQueuedCompletionStatus function retrieves these queued completion packets.

A server application may have several threads calling GetQueuedCompletionStatus for the same completion port. As input operations complete, the operating system queues completion packets to the completion port. If threads are actively waiting in a call to this function, queued requests complete their call. For more information, see I/O Completion Ports.

You can call the PostQueuedCompletionStatus function to post an completion packet to an completion port. The completion packet will satisfy an outstanding call to the GetQueuedCompletionStatus function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, ConnectNamedPipe, CreateIoCompletionPort, DeviceIoControl, LockFileEx, OVERLAPPED, ReadFile, PostQueuedCompletionStatus, TransactNamedPipe, WaitCommEvent, WriteFile


GetShortPathName

The GetShortPathName function retrieves the short path form of a specified input path.

DWORD GetShortPathName(
  LPCTSTR lpszLongPath,  // null-terminated path string
  LPTSTR lpszShortPath,  // short form buffer
  DWORD cchBuffer        // size of short form buffer
);

Parameters

lpszLongPath
[in] Pointer to a null-terminated path string. The function retrieves the short form of this path.

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

lpszShortPath
[out] Pointer to a buffer to receive the null-terminated short form of the path specified by lpszLongPath.
cchBuffer
[in] Specifies the size, in TCHARs, of the buffer pointed to by lpszShortPath.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpszShortPath, not including the terminating null character.

If the lpszShortPath buffer is too small to contain the path, the return value is the size of the buffer, in TCHARs, required to hold the path. Therefore, if the return value is greater than cchBuffer, call the function again with a buffer that is large enough to hold the path.

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

Remarks

When an application calls this function and specifies a path on a volume that does not support 8.3 aliases, the function fails with ERROR_INVALID_PARAMETER if the path is longer than 67 bytes.

The path specified by lpszLongPath does not have to be a full or a long path. The short form may be longer than the specifed path.

If the specified path is already in its short form, there is no need for any conversion, and the function simply copies the specified path to the buffer for the short path.

You can set lpszShortPath to the same value as lpszLongPath; in other words, you can set the buffer for the short path to the address of the input path string.

You can obtain the long name of a file from the short name by calling the GetLongPathName function. Alternatively, where GetLongPathName is not available, you can call FindFirstFile on each component of the path to get the corresponding long name.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, FindFirstFile, GetFullPathName, GetLongPathName, SetFileShortName


GetTempFileName

The GetTempFileName function creates a name for a temporary file. The file name is the concatenation of specified path and prefix strings, a hexadecimal string formed from a specified integer, and the .tmp extension.

The specified integer can be nonzero, in which case, the function creates the file name but does not create the file. If you specify zero for the integer, the function creates a unique file name and creates the file in the specified directory.

UINT GetTempFileName(
  LPCTSTR lpPathName,      // directory name
  LPCTSTR lpPrefixString,  // file name prefix
  UINT uUnique,            // integer
  LPTSTR lpTempFileName    // file name buffer
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the directory path for the file name. This string must consist of characters in the ANSI character set. Applications typically specify a period (.) or the result of the GetTempPath function for this parameter. If this parameter is NULL, the function fails.
lpPrefixString
[in] Pointer to a null-terminated prefix string. The function uses the first three characters of this string as the prefix of the file name. This string must consist of characters in the ANSI character set.
uUnique
[in] Specifies an unsigned integer that the function converts to a hexadecimal string for use in creating the temporary file name.

If uUnique is nonzero, the function appends the hexadecimal string to lpPrefixString to form the temporary file name. In this case, the function does not create the specified file, and does not test whether the file name is unique.

If uUnique is zero, the function creates the file in the lpPathName directory using a unique file name.

lpTempFileName
[out] Pointer to the buffer that receives the temporary file name. This null-terminated string consists of characters in the ANSI character set. This buffer should be at least the length, in bytes, specified by MAX_PATH to accommodate the path.

Return Values

If the function succeeds, the return value specifies the unique numeric value used in the temporary file name. If the uUnique parameter is nonzero, the return value specifies that same number.

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

Remarks

The GetTempFileName function creates a temporary file name of the following form:

path\preuuuu.TMP

The following table describes the file name syntax.

Component | Meaning
path | Path specified by the lpPathName parameter
pre | First three letters of the lpPrefixString string
uuuu | Hexadecimal value of uUnique

When the system shuts down, temporary files whose names have been created by this function are not automatically deleted.

To avoid problems resulting when converting an ANSI string, an application should call the CreateFile function to create a temporary file.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Creating and Using a Temporary File.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CreateFile, GetTempPath


GetTempPath

The GetTempPath function retrieves the path of the directory designated for temporary files.

DWORD GetTempPath(
  DWORD nBufferLength,  // size of buffer
  LPTSTR lpBuffer       // path buffer
);

Parameters

nBufferLength
[in] Specifies the size, in TCHARs, of the string buffer identified by lpBuffer.
lpBuffer
[out] Pointer to a string buffer that receives the null-terminated string specifying the temporary file path. The returned string ends with a backslash, for example, C:\TEMP\.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the terminating null character. If the return value is greater than nBufferLength, the return value is the size of the buffer required to hold the path.

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

Remarks

Windows 95/98/Me: The GetTempPath function gets the temporary file path as follows:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable, if TMP is not defined or if TMP specifies a directory that does not exist.
  3. The current directory, if both TMP and TEMP are not defined or specify nonexistent directories.

Windows NT/2000 or later: The GetTempPath function does not verify that the directory specified by the TMP or TEMP environment variables exists. The function gets the temporary file path as follows:

  1. The path specified by the TMP environment variable.
  2. The path specified by the TEMP environment variable, if TMP is not defined.
  3. The Windows directory, if both TMP and TEMP are not defined.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetTempFileName


LockFile

The LockFile function locks a region in an open file. Locking a region prevents other processes from accessing the region.

To specify additional options, use the LockFileEx function.

BOOL LockFile(
  HANDLE hFile,                   // handle to file
  DWORD dwFileOffsetLow,          // low-order word of offset
  DWORD dwFileOffsetHigh,         // high-order word of offset
  DWORD nNumberOfBytesToLockLow,  // low-order word of length
  DWORD nNumberOfBytesToLockHigh  // high-order word of length
);

Parameters

hFile
[in] Handle to the file with a region to be locked. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file (or both).
dwFileOffsetLow
[in] Specifies the low-order word of the starting byte offset in the file where the lock should begin.
dwFileOffsetHigh
[in] Specifies the high-order word of the starting byte offset in the file where the lock should begin.

Windows 95/98/Me: dwFileOffsetHigh must be 0, the sign extension of the value of dwFileOffsetLow. Any other value will be rejected.

nNumberOfBytesToLockLow
[in] Specifies the low-order word of the length of the byte range to be locked.
nNumberOfBytesToLockHigh
[in] Specifies the high-order word of the length of the byte range to be locked.

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

Locking a region of a file gives the locking process exclusive access to the specified region. File locks are not inherited by processes created by the locking process.

Locking a region of a file denies all other processes both read and write access to the specified region. Locking a region that goes beyond the current end-of-file position is not an error.

Locks may not overlap an existing locked region of the file.

If LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request that will block until the lock is acquired, use LockFileEx without LOCKFILE_FAIL_IMMEDIATELY.

The UnlockFile function unlocks a file region locked by LockFile.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, LockFileEx, UnlockFile


LockFileEx

The LockFileEx function locks a region in an open file for shared or exclusive access. Locking a region prevents other processes from accessing the region.

BOOL LockFileEx(
  HANDLE hFile,                   // handle to file
  DWORD dwFlags,                  // lock options
  DWORD dwReserved,               // reserved
  DWORD nNumberOfBytesToLockLow,  // low-order word of length
  DWORD nNumberOfBytesToLockHigh, // high-order word of length
  LPOVERLAPPED lpOverlapped       // contains starting offset
);

Parameters

hFile
[in] Handle to an open handle to a file that is to have a range of bytes locked for shared or exclusive access. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.
dwFlags
[in] Specifies flags that modify the behavior of this function. This parameter may be one or more of the following values.
Value | Meaning
LOCKFILE_FAIL_IMMEDIATELY | If this value is specified, the function returns immediately if it is unable to acquire the requested lock. Otherwise, it waits.
LOCKFILE_EXCLUSIVE_LOCK | If this value is specified, the function requests an exclusive lock. Otherwise, it requests a shared lock.

dwReserved
Reserved parameter; must be set to zero.
nNumberOfBytesToLockLow
[in] Specifies the low-order 32 bits of the length of the byte range to lock.
nNumberOfBytesToLockHigh
[in] Specifies the high-order 32 bits of the length of the byte range to lock.
lpOverlapped
[in] Pointer to an OVERLAPPED structure that the function uses with the locking request. This structure, which is required, contains the file offset of the beginning of the lock range. You must initialize the hEvent member to a valid handle or zero.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Locking a region of a file is used to acquire shared or exclusive access to the specified region of the file. File locks are not inherited by a new process during process creation.

Locking a portion of a file for exclusive access denies all other processes both read and write access to the specified region of the file. Locking a region that goes beyond the current end-of-file position is not an error.

Locking a portion of a file for shared access denies all processes write access to the specified region of the file, including the process that first locks the region. All processes can read the locked region.

The LockFileEx function operates asynchronously if the file handle was opened for asynchronous I/O, unless the LOCKFILE_FAIL_IMMEDIATELY flag is specified. If an exclusive lock is requested for a range of a file that already has a shared or exclusive lock, the function returns the error ERROR_IO_PENDING. The system will signal the event specified in the OVERLAPPED structure after the lock is granted. To determine when the lock has been granted, use the GetOverlappedResult function or one of the wait functions.

If the file handle was not opened for asynchronous I/O and the lock is not available, this call waits until the lock is granted or an error occurs, unless the LOCKFILE_FAIL_IMMEDIATELY flag is specified.

Locks may not overlap an existing locked region of the file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, LockFile, OVERLAPPED, UnlockFile, UnlockFileEx


MoveFile

The MoveFile function moves an existing file or a directory, including its children.

To specify how to move the file, use the MoveFileEx function.

BOOL MoveFile(
  LPCTSTR lpExistingFileName, // file name
  LPCTSTR lpNewFileName       // new file name
);

Parameters

lpExistingFileName
[in] Pointer to a null-terminated string that names an existing file or directory.

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

lpNewFileName
[in] Pointer to a null-terminated string that specifies the new name of a file or directory. The new name must not already exist. A new file may be on a different file system or drive. A new directory must be on the same drive.

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

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

The MoveFile function will move (rename) either a file or a directory (including its children) either in the same directory or across directories. The one caveat is that the MoveFile function will fail on directory moves when the destination is on a different volume.

Windows 2000 and later: The MoveFile function coordinates its operation with the link tracking service, so link sources can be tracked as they are moved.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

For example, see Creating and Using a Temporary File.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CopyFile, MoveFileEx, MoveFileWithProgress


MoveFileEx

The MoveFileEx function moves an existing file or directory.

The MoveFileWithProgress function is equivalent to the MoveFileEx function, except that MoveFileWithProgress allows you to provide a callback function that receives progress notifications.

BOOL MoveFileEx(
  LPCTSTR lpExistingFileName,  // file name
  LPCTSTR lpNewFileName,       // new file name
  DWORD dwFlags                // move options
);

Parameters

lpExistingFileName
[in] Pointer to a null-terminated string that names an existing file or directory on the local machine. 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.

If dwflags specifies MOVEFILE_DELAY_UNTIL_REBOOT, the file cannot have the read-only attribute.

lpNewFileName
[in] Pointer to a null-terminated string that specifies the new name of lpExistingFileName on the local machine.

When moving a file, the destination can be on a different file system or drive. If the destination is on another drive, you must set the MOVEFILE_COPY_ALLOWED flag in dwFlags.

When moving a directory, the destination must be on the same drive.

If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, lpNewFileName can be NULL. In this case, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.

dwFlags
[in] Specifies how to move the file. This parameter can be one or more of the following values.
Value | Meaning
MOVEFILE_COPY_ALLOWED If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.

This value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
MOVEFILE_CREATE_HARDLINK | Reserved for future use.
MOVEFILE_DELAY_UNTIL_REBOOT The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.

This value can be used only if the process is in the context of a user who belongs to the administrator group or the LocalSystem account.

This value cannot be used with MOVEFILE_COPY_ALLOWED.
MOVEFILE_FAIL_IF_NOT_TRACKABLE | Windows 2000 and later: The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the destination is a volume formatted with the FAT file system.
MOVEFILE_REPLACE_EXISTING If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file.

This value cannot be used if lpNewFileName or lpExistingFileName names a directory.

MOVEFILE_WRITE_THROUGH The function does not return until the file has actually been moved on the disk.

Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation.

This value has no effect if MOVEFILE_DELAY_UNTIL_REBOOT is set.

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

If the dwFlags parameter specifies MOVEFILE_DELAY_UNTIL_REBOOT, MoveFileEx stores the locations of the files to be renamed at restart in the following registry value:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations

The function fails if it cannot access the registry.

The PendingFileRenameOperations value is of type REG_MULTI_SZ. Each rename operation stores a pair of NULL-terminated strings. The system uses these registry entries to complete the operations at restart in the same order that they were issued. For example, the following code fragment creates registry entries that delete szDstFile and rename szSrcFile to be szDstFile at restart:

MoveFileEx(szDstFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
MoveFileEx(szSrcFile, szDstFile, MOVEFILE_DELAY_UNTIL_REBOOT);

The system stores the following entries in PendingFileRenameOperations:

szDstFile\0\0
szSrcFile\0szDstFile\0\0

Because the actual move and deletion operations specified with the MOVEFILE_DELAY_UNTIL_REBOOT flag take place after the calling application has ceased running, the return value cannot reflect success or failure in moving or deleting the file. Rather, it reflects success or failure in placing the appropriate entries into the registry.

The system deletes a directory tagged for deletion with the MOVEFILE_DELAY_UNTIL_REBOOT flag only if it is empty. To ensure deletion of directories, move or delete all files from the directory before attempting to delete it. Files may be in the directory at boot time, but they must be deleted or moved before the system can delete the directory.

The move and deletion operations are carried out at boot time in the same order they are specified in the calling application. To delete a directory that has files in it at boot time, first delete the files.

Windows 2000 and later: The MoveFileEx function coordinates its operation with the link tracking service, so link sources can be tracked as they are moved.

Windows 95/98/Me: The MoveFileEx function is not supported. To rename or delete a file at restart, use the following procedure.

To rename or delete a file on Windows 95/98

  1. Check for the existence of the WININIT.INI file in the Windows directory.
  2. If WININIT.INI exists, open it and add new entries to the existing [rename] section. If the file does not exist, create the file and create a [rename] section.
  3. Add lines of the following format to the [rename] section:
    DestinationFileName=SourceFileName

    Both DestinationFileName and SourceFileName must be short file names. To delete a file, use NUL as the value for DestinationFileName.

The system processes WININIT.INI during system boot. After WININIT.INI has been processed, the system names it WININIT.BAK.

To delete or rename a file, you must have either delete permission on the file or delete child permission in the parent directory. If you set up a directory with all access except delete and delete child and the ACLs of new files are inherited, then you should be able to create a file without being able to delete it. However, you can then create a file, and you will get all the access you request on the handle returned to you at the time you create the file. If you requested delete permission at the time you created the file, you could delete or rename the file with that handle but not with any other.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File I/O Overview, File I/O Functions, CopyFile, DeleteFile, GetWindowsDirectory, MoveFileWithProgress, WritePrivateProfileString


MoveFileWithProgress

The MoveFileWithProgress function moves a file or directory. MoveFileWithProgress is equivalent to the MoveFileEx function, except that MoveFileWithProgress allows you to provide a callback function that receives progress notifications.

BOOL MoveFileWithProgress(
  LPCTSTR lpExistingFileName,            // file name
  LPCTSTR lpNewFileName,                 // new file name
  LPPROGRESS_ROUTINE lpProgressRoutine,  // callback function
  LPVOID lpData,                         // parameter for callback
  DWORD dwFlags                          // move options
);

Parameters

lpExistingFileName
[in] Pointer to a null-terminated string that names an existing file or directory on the local machine.

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

lpNewFileName
[in] Pointer to a null-terminated string containing the new name of the file or directory.

When moving a file, lpNewFileName can be on a different file system or drive. If lpNewFileName is on another drive, you must set the MOVEFILE_COPY_ALLOWED flag in dwFlags.

When moving a directory, lpExistingFileName and lpNewFileName must be on the same drive.

If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT, lpNewFileName can be NULL. In this case, MoveFileEx registers lpExistingFileName to be deleted when the system restarts. The function fails if it cannot access the registry to store the information about the delete operation. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.

lpProgressRoutine
[in] Pointer to a CopyProgressRoutine callback function that is called each time another portion of the file has been moved. The callback function can be useful if you provide a user interface that displays the progress of the operation. This parameter can be NULL.
lpData
[in] Specifies an argument that MoveFileWithProgress passes to the CopyProgressRoutine callback function. This parameter can be NULL.
dwFlags
[in] Specifies how to move the file. This parameter can be one or more of the following values.
Value | Meaning
MOVEFILE_COPY_ALLOWED If the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions.

This value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
MOVEFILE_CREATE_HARDLINK | Reserved for future use.
MOVEFILE_DELAY_UNTIL_REBOOT The system does not move the file until the operating system is restarted. The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. Consequently, this parameter enables the function to delete paging files from previous startups.

This value can only be used if the process is in the context of a user who belongs to the administrator group or the LocalSystem account.

This value cannot be used with MOVEFILE_COPY_ALLOWED.
MOVEFILE_FAIL_IF_NOT_TRACKABLE | The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the destination is a volume formatted with the FAT file system.
MOVEFILE_REPLACE_EXISTING If a file named lpNewFileName exists, the function replaces its contents with the contents of the lpExistingFileName file.

This value cannot be used if lpNewFileName or lpExistingFileName names a directory.

MOVEFILE_WRITE_THROUGH The function does not return until the file has actually been moved on the disk.

Setting this value guarantees that a move performed as a copy and delete operation is flushed to disk before the function returns. The flush occurs at the end of the copy operation.

This value has no effect if MOVEFILE_DELAY_UNTIL_REBOOT is set.

Return Value

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

The MoveFileWithProgress function coordinates its operation with the link tracking service, so link sources can be tracked as they are moved.

To delete or rename a file, you must have either delete permission on the file or delete child permission in the parent directory. If you set up a directory with all access except delete and delete child and the ACLs of new files are inherited, then you should be able to create a file without being able to delete it. However, you can then create a file, and you will get all the access you request on the handle returned to you at the time you create the file. If you requested delete permission at the time you created the file, you could delete or rename the file with that handle but not with any other.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File I/O Overview, File I/O Functions, CopyFileEx, CopyProgressRoutine, MoveFileEx


OpenFile

The OpenFile function creates, opens, reopens, or deletes a file.

Note This function is provided only for compatibility with 16-bit versions of Windows. New applications should use the CreateFile function.

HFILE OpenFile(
  LPCSTR lpFileName,        // file name
  LPOFSTRUCT lpReOpenBuff,  // file information
  UINT uStyle               // action and attributes
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that names the file to be opened. The string must consist of characters from the Windows 3.x character set. The OpenFile function does not support Unicode file names. Also, OpenFile does not support opening named pipes.
lpReOpenBuff
[out] Pointer to the OFSTRUCT structure that receives information about the file when it is first opened. The structure can be used in subsequent calls to the OpenFile function to refer to the open file.

The OFSTRUCT structure contains a pathname string member whose length is limited to OFS_MAXPATHNAME characters. OFS_MAXPATHNAME is currently defined to be 128. Because of this, you cannot use the OpenFile function to open a file whose path length exceeds 128 characters. The CreateFile function does not have such a path length limitation.

uStyle
[in] Specifies the action to take. This parameter can be one or more of the following values.
Value | Meaning
OF_CANCEL | Ignored. To produce a dialog box containing a Cancel button, use OF_PROMPT.
OF_CREATE | Creates a new file. If the file already exists, it is truncated to zero length.
OF_DELETE | Deletes the file.
OF_EXIST | Opens the file and then closes it. Used to test for a file's existence.
OF_PARSE | Fills the OFSTRUCT structure but carries out no other action.
OF_PROMPT | Displays a dialog box if the requested file does not exist. The dialog box informs the user that the system cannot find the file, and it contains Retry and Cancel buttons. Choosing the Cancel button directs OpenFile to return a file-not-found error message.
OF_READ | Opens the file for reading only.
OF_READWRITE | Opens the file for reading and writing.
OF_REOPEN | Opens the file using information in the reopen buffer.
OF_SHARE_COMPAT For MS-DOS–based file systems, opens the file with compatibility mode, allowing any process on a specified computer to open the file any number of times. Other efforts to open with any other sharing mode fail.

Windows NT/2000 or later: This flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_NONE Opens the file without denying read or write access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode by any other process, the function fails.

Windows NT/2000 or later: This flag is mapped to the CreateFile function's FILE_SHARE_READ | FILE_SHARE_WRITE flags.
OF_SHARE_DENY_READ Opens the file and denies read access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode or for read access by any other process, the function fails.

Windows NT/2000 or later: This flag is mapped to the CreateFile function's FILE_SHARE_WRITE flag.
OF_SHARE_DENY_WRITE Opens the file and denies write access to other processes. On MS-DOS-based file systems, if the file has been opened in compatibility mode or for write access by any other process, the function fails.

Windows NT/2000 or later: This flag is mapped to the CreateFile function's FILE_SHARE_READ flag.
OF_SHARE_EXCLUSIVE | Opens the file with exclusive mode, denying both read and write access to other processes. If the file has been opened in any other mode for read or write access, even by the current process, the function fails.
OF_VERIFY | Verifies that the date and time of the file are the same as when it was previously opened. This is useful as an extra check for read-only files.
OF_WRITE | Opens the file for writing only.

Return Values

If the function succeeds, the return value specifies a file handle.

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

Remarks

If the lpFileName parameter specifies a file name and extension only, this function searches for a matching file in the following directories, in the order shown:

  1. The directory from which the application loaded.
  2. The current directory.
  3. Windows 95/98/Me: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

    Windows NT/2000 or later: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

  4. Windows NT/2000 or later: The 16-bit Windows system directory. There is no function that retrieves the path of this directory, but it is searched. The name of this directory is SYSTEM.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

The lpFileName parameter cannot contain wildcard characters.

The OpenFile function does not support the OF_SEARCH flag supported by the 16-bit Windows OpenFile function. The OF_SEARCH flag directs the system to search for a matching file even when the file name includes a full path. To search for a file, use the SearchPath function.

To close the file after use, call the _lclose function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, GetSystemDirectory, GetWindowsDirectory, _lclose, OFSTRUCT, SearchPath


PostQueuedCompletionStatus

The PostQueuedCompletionStatus function posts an I/O completion packet to an I/O completion port. The I/O completion packet will satisfy an outstanding call to the GetQueuedCompletionStatus function. The GetQueuedCompletionStatus function returns with the three values passed as the second, third, and fourth parameters of the call to PostQueuedCompletionStatus.

BOOL PostQueuedCompletionStatus(
  HANDLE CompletionPort,            // handle to an I/O completion port
  DWORD dwNumberOfBytesTransferred, // bytes transferred
  ULONG_PTR dwCompletionKey,        // completion key
  LPOVERLAPPED lpOverlapped         // overlapped buffer
);

Parameters

CompletionPort
[in] Handle to an I/O completion port to which the I/O completion packet is to be posted.
dwNumberOfBytesTransferred
[in] Specifies a value to be returned through the lpNumberOfBytesTransferred parameter of the GetQueuedCompletionStatus function.
dwCompletionKey
[in] Specifies a value to be returned through the lpCompletionKey parameter of the GetQueuedCompletionStatus function.
lpOverlapped
[in] Specifies a value to be returned through the lpOverlapped parameter of the GetQueuedCompletionStatus function.

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

For more information concerning dwNumberOfBytesTransferred, dwCompletionKey, and lpOverlapped, see GetQueuedCompletionStatus and the descriptions of the parameters those values are returned through.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateIoCompletionPort, GetQueuedCompletionStatus, OVERLAPPED


QueryDosDevice

The QueryDosDevice function retrieves information about MS-DOS device names. The function can obtain the current mapping for a particular MS-DOS device name. The function can also obtain a list of all existing MS-DOS device names.

MS-DOS device names are stored as symbolic links in the object name space. The code that converts an MS-DOS path into a corresponding path uses these symbolic links to map MS-DOS devices and drive letters. The QueryDosDevice function provides a mechanism whereby an application can query the names of the symbolic links used to implement the MS-DOS device namespace as well as the value of each specific symbolic link.

DWORD QueryDosDevice(
  LPCTSTR lpDeviceName, // MS-DOS device name string
  LPTSTR lpTargetPath,  // query results buffer
  DWORD ucchMax         // maximum size of buffer
);

Parameters

lpDeviceName
[in] Pointer to an MS-DOS device name string specifying the target of the query. The device name cannot have a trailing backslash.

This parameter can be NULL. In that case, the QueryDosDevice function will store a list of all existing MS-DOS device names into the buffer pointed to by lpTargetPath.

lpTargetPath
[out] Pointer to a buffer that will receive the result of the query. The function fills this buffer with one or more null-terminated strings. The final null-terminated string is followed by an additional NULL.

If lpDeviceName is non-NULL, the function retrieves information about the particular MS-DOS device specified by lpDeviceName. The first null-terminated string stored into the buffer is the current mapping for the device. The other null-terminated strings represent undeleted prior mappings for the device.

If lpDeviceName is NULL, the function retrieves a list of all existing MS-DOS device names. Each null-terminated string stored into the buffer is the name of an existing MS-DOS device.

ucchMax
[in] Specifies the maximum number of TCHARs that can be stored into the buffer pointed to by lpTargetPath.

Return Values

If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by lpTargetPath.

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

Remarks

The DefineDosDevice function provides a means whereby an application can create and modify the symbolic links used to implement the MS-DOS device namespace.

MS-DOS device names are global. After is it defined, an MS-DOS device name remains visible to all processes until either it is explicitly removed or the system restarts.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 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.

See Also

File I/O Overview, File I/O Functions, DefineDosDevice


ReadDirectoryChangesW

The ReadDirectoryChangesW function retrieves information describing the changes occurring within a directory.

BOOL ReadDirectoryChangesW(
  HANDLE hDirectory,                                  // handle to directory
  LPVOID lpBuffer,                                    // read results buffer
  DWORD nBufferLength,                                // length of buffer
  BOOL bWatchSubtree,                                 // monitoring option
  DWORD dwNotifyFilter,                               // filter conditions
  LPDWORD lpBytesReturned,                            // bytes returned
  LPOVERLAPPED lpOverlapped,                          // overlapped buffer
  LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // completion routine
);

Parameters

hDirectory
[in] Handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right.
lpBuffer
[in/out] Pointer to the formatted buffer in which the read results are to be returned. The structure of this buffer is defined by the FILE_NOTIFY_INFORMATION structure. This buffer is filled either synchronously or asynchronously, depending on how the directory is opened and what value is given to the lpOverlapped parameter. For more information, see the Remarks section.
nBufferLength
[in] Specifies the length of the buffer pointed to by the lpBuffer parameter, in bytes.
bWatchSubtree
[in] Specifies whether the ReadDirectoryChangesW function will monitor the directory or the directory tree. If TRUE is specified, the function monitors the directory tree rooted at the specified directory. If FALSE is specified, the function monitors only the directory specified by the hDirectory parameter.
dwNotifyFilter
[in] Specifies filter criteria the function checks to determine if the wait operation has completed. This parameter can be one or more of the following values.
Value | Meaning
FILE_NOTIFY_CHANGE_FILE_NAME | Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes include renaming, creating, or deleting a file.
FILE_NOTIFY_CHANGE_DIR_NAME | Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes include creating or deleting a directory.
FILE_NOTIFY_CHANGE_ATTRIBUTES | Any attribute change in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SIZE | Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_WRITE | Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_ACCESS | Any change to the last access time of files in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_CREATION | Any change to the creation time of files in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SECURITY | Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.

lpBytesReturned
[out] For synchronous calls, this parameter receives the number of bytes transferred into the lpBuffer parameter. For asynchronous calls, this parameter is undefined. You must use an asynchronous notification technique to retrieve the number of bytes transferred.
lpOverlapped
[in] Pointer to an OVERLAPPED structure that supplies data to be used during asynchronous operation. Otherwise, this value is NULL. The Offset and OffsetHigh members of this structure are not used.
lpCompletionRoutine
[in] Pointer to a completion routine to be called when the operation has been completed or canceled and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.

Return Values

If the function succeeds, the return value is nonzero. For synchronous calls, this means that the operation succeeded. For asynchronous calls, this indicates that the operation was successfully queued.

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

Remarks

To obtain a handle to a directory, use the CreateFile function with FILE_FLAG_BACKUP_SEMANTICS as follows:

hDir = CreateFile(
  DirName,                            // pointer to the file name
  FILE_LIST_DIRECTORY,                // access (read/write) mode
  FILE_SHARE_READ|FILE_SHARE_DELETE,  // share mode
  NULL,                               // security descriptor
  OPEN_EXISTING,                      // how to create
  FILE_FLAG_BACKUP_SEMANTICS,         // file attributes
  NULL                                // file with attributes to copy
);

A call to ReadDirectoryChangesW can be completed synchronously or asynchronously. To specify asynchronous completion, open the directory with CreateFile as shown above, but additionally specify the FILE_FLAG_OVERLAPPED attribute in the dwFlagsAndAttributes parameter. Then specify an OVERLAPPED structure when you call ReadDirectoryChangesW.

Upon successful synchronous completion, the lpBuffer parameter is a formatted buffer and the number of bytes written to the buffer is available in lpBytesReturned. If the number of bytes transferred is zero, the buffer was too small to provide detailed information on all the changes that occurred in the directory or subtree. In this case, you should compute the changes by enumerating the directory or subtree.

For asynchronous completion, you can receive notification in one of three ways:

  • Using the GetOverlappedResult function. To receive notification through GetOverlappedResult, do not specify a completion routine in the lpCompletionRoutine parameter. Be sure to set the hEvent member of the OVERLAPPED structure to a unique event.
  • Using the GetQueuedCompletionStatus function. To receive notification through GetQueuedCompletionStatus, do not specify a completion routine in lpCompletionRoutine. Associate the directory handle hDirectory with a completion port by calling the CreateIoCompletionPort function.
  • Using a completion routine. To receive notification through a completion routine, do not associate the directory with a completion port. Specify a completion routine in lpCompletionRoutine. This routine is called whenever the operation has been completed or canceled while the thread is in an alertable wait state. The hEvent member of the OVERLAPPED structure is not used by the system, so you can use it yourself.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 SP3 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented only as Unicode.

See Also

File I/O Overview, File I/O Functions, CreateFile, CreateIoCompletionPort, FILE_NOTIFY_INFORMATION, FileIOCompletionRoutine, GetOverlappedResult, GetQueuedCompletionStatus, OVERLAPPED


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 or later: 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 or later: 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 or later: 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 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're 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're 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

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CancelIo, CreateFile, GetCommTimeouts, GetOverlappedResult, GetQueuedCompletionStatus, OVERLAPPED, PeekNamedPipe, ReadFileEx, SetCommTimeouts, SetErrorMode, WriteFile


ReadFileEx

The ReadFileEx function reads data from a file asynchronously. It is designed solely for asynchronous operation, unlike the ReadFile function, which is designed for both synchronous and asynchronous operation. ReadFileEx lets an application perform other processing during a file read operation.

The ReadFileEx function reports its completion status asynchronously, calling a specified completion routine when reading is completed or canceled and the calling thread is in an alertable wait state.

BOOL ReadFileEx(
  HANDLE hFile,                                       // handle to file
  LPVOID lpBuffer,                                    // data buffer
  DWORD nNumberOfBytesToRead,                         // number of bytes to read
  LPOVERLAPPED lpOverlapped,                          // offset
  LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // completion routine
);

Parameters

hFile
[in] Handle to the file to be read. This file handle must have been created with the FILE_FLAG_OVERLAPPED flag and must have GENERIC_READ access to the file.

Windows NT/2000 or later: This parameter 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: This parameter 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 a buffer that receives the data read from the file.

This buffer must remain valid for the duration of the read operation. The application should not use this buffer until the read operation is completed.

nNumberOfBytesToRead
[in] Specifies the number of bytes to be read from the file.
lpOverlapped
[in] Pointer to an OVERLAPPED data structure that supplies data to be used during the asynchronous (overlapped) file read operation.

If the file specified by hFile supports the concept of byte offsets, the caller of ReadFileEx must specify a byte offset within the file at which reading should begin. The caller specifies the byte offset by setting the OVERLAPPED structure's Offset and OffsetHigh members.

The ReadFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a ReadFileEx call. ReadFileEx signals completion of its read operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The ReadFileEx function does use the OVERLAPPED structure's Internal and InternalHigh members. An application should not set these members.

The OVERLAPPED data structure pointed to by lpOverlapped must remain valid for the duration of the read operation. It should not be a variable that can go out of scope while the file read operation is in progress.

lpCompletionRoutine
[in] Pointer to the completion routine to be called when the read operation is complete and the calling thread is in an alertable wait state. For more information about the completion routine, see FileIOCompletionRoutine.

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.

If the function succeeds, the calling thread has an asynchronous input/output (I/O) operation pending: the overlapped read operation from the file. When this I/O operation completes, and the calling thread is blocked in an alertable wait state, the system calls the function pointed to by lpCompletionRoutine, and the wait state completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds, and the file reading operation completes, but the calling thread is not in an alertable wait state, the system queues the completion routine call, holding the call until the calling thread enters an alertable wait state. For information about alertable waits and overlapped input/output operations, see Synchronization and Overlapped Input and Output.

If ReadFileEx attempts to read past the end of the file, the function returns zero, and GetLastError returns ERROR_HANDLE_EOF.

Remarks

When using ReadFileEx you should check GetLastError even when the function returns "success" to check for conditions that are "successes" but have some outcome you might want to know about. For example, a buffer overflow when calling ReadFileEx will return TRUE, but GetLastError will report the overflow with ERROR_MORE_DATA. If the function call is successful and there are no warning conditions, GetLastError will return ERROR_SUCCESS.

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 a portion of the file specified by hFile is locked by another process, and the read operation specified in a call to ReadFileEx overlaps the locked portion, the call to ReadFileEx fails.

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

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.

The ReadFileEx function may fail if there are too many outstanding asynchronous I/O requests. In the event of such a failure, GetLastError can return ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY.

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.

An application uses the MsgWaitForMultipleObjectsEx, WaitForSingleObjectEx, WaitForMultipleObjectsEx, and SleepEx functions to enter an alertable wait state. For more information about alertable waits and overlapped input/output, refer to those functions' reference and Synchronization.

Windows 95/98/Me: On this platform, neither ReadFileEx nor WriteFileEx can be used by the comm ports to communicate. However, you can use ReadFile and WriteFile to perform asynchronous communication.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CancelIo, CreateFile, FileIOCompletionRoutine, MsgWaitForMultipleObjectsEx, OVERLAPPED, ReadFile, SetErrorMode, SleepEx, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFileEx


ReadFileScatter

The ReadFileScatter function reads data from a file and stores the data into a set of buffers.

The function starts reading data from the file at a position specified by an OVERLAPPED structure. It operates asynchronously.

BOOL ReadFileScatter(
  HANDLE hFile,                          // handle to file
  FILE_SEGMENT_ELEMENT aSegmentArray[ ], // array of buffer pointers
  DWORD nNumberOfBytesToRead,            // number of bytes to read
  LPDWORD lpReserved,                    // reserved; must be NULL
  LPOVERLAPPED lpOverlapped              // OVERLAPPED structure
);

Parameters

hFile
[in] Handle to the file to be read.

This file handle must have been created using GENERIC_READ to specify read access to the file, FILE_FLAG_OVERLAPPED to specify asynchronous I/O, and FILE_FLAG_NO_BUFFERING to specify non-cached I/O.

aSegmentArray
[in] Pointer to an array of FILE_SEGMENT_ELEMENT buffers. The array must contain one member for each system memory page-sized chunk of the total number of bytes to read from the file, plus one member for the final NULL pointer. For example, if the number of bytes to read is 40K, and the system page size is 4K, then this array must have 10 members for data, plus one member for the final NULL member, for a total of 11 members.

Each buffer must be at least the size of a system memory page and must be aligned on a system memory page size boundary. The system will read one system memory page of data into each buffer.

The function stores the data into the buffers in a sequential manner: it stores data into the first buffer, then into the second buffer, then into the next, filling each buffer, until there is no more data or there are no more buffers.

The final element of the array must be a 64-bit NULL pointer.

nNumberOfBytesToRead
[in] Specifies the total number of bytes to read from the file; each element of aSegmentArray contains a 1-page chunk of this total. Because the file must be opened with FILE_FLAG_NO_BUFFERING, the number of bytes to write must be a multiple of the sector size of the file system on which the file resides.
lpReserved
[in] This parameter is reserved for future use. You must set it to NULL.
lpOverlapped
[in] Pointer to an OVERLAPPED data structure.

The ReadFileScatter function requires a valid OVERLAPPED structure. The lpOverlapped parameter cannot be NULL.

The ReadFileScatter function starts reading data from the file at a position specified by the Offset and OffsetHigh members of the OVERLAPPED structure.

The ReadFileScatter function may return before the read operation has completed. In that case, the ReadFileScatter function returns the value zero, and the GetLastError function returns the value ERROR_IO_PENDING. This asynchronous operation of ReadFileScatter lets the calling process continue while the read operation completes. You can call the GetOverlappedResult, HasOverlappedIoCompleted, or GetQueuedCompletionStatus function to obtain information about the completion of the read operation.

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 the GetLastError function.

If the function attempts to read past the end of the file, the function returns zero, and GetLastError returns ERROR_HANDLE_EOF.

If the function returns before the read operation has completed, the function returns zero, and GetLastError returns ERROR_IO_PENDING.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP2 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, GetOverlappedResult, GetQueuedCompletionStatus, HasOverlappedIoCompleted, OVERLAPPED, ReadFile, ReadFileEx, WriteFileGather


RemoveDirectory

The RemoveDirectory function deletes an existing empty directory.

BOOL RemoveDirectory(
  LPCTSTR lpPathName   // directory name
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the path of the directory to be removed. The path must specify an empty directory, and the calling process must have delete access to the directory.

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

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

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, CreateDirectory


ReplaceFile

The ReplaceFile function replaces one file with another file, with the option of creating a backup copy of the original file. The replacement file assumes the name of the replaced file and its identity.

BOOL ReplaceFile(
  LPCTSTR lpReplacedFileName,    // file name
  LPCTSTR lpReplacementFileName, // replacement file
  LPCTSTR lpBackupFileName,      // optional backup file
  DWORD dwReplaceFlags,          // replace options
  LPVOID lpExclude,              // reserved
  LPVOID lpReserved              // reserved
);

Parameters

lpReplacedFileName
[in] Pointer to a null-terminated string that specifies the name of the file that will be replaced by the lpReplacementFileName file.

This file is opened with the GENERIC_READ, DELETE, and SYNCHRONIZE access rights. The sharing mode is FILE_SHARE_READ | FILE_SHARED_WRITE | FILE_SHARE_DELETE.

The caller must have write access to the file to be replaced.

lpReplacementFileName
[in] Pointer to a null-terminated string that specifies the name of the file that will replace the lpReplacedFileName file.

The function attemps to open this file with the SYNCHRONIZE, GENERIC_READ, GENERIC_WRITE, DELETE, and WRITE_DAC access rights. If this fails, the function attemps to open the file with the SYNCHRONIZE, GENERIC_READ, DELETE, and WRITE_DAC access rights. No sharing mode is specified.

lpBackupFileName
[in] Pointer to a null-terminated string that specifies the name of the file that will serve as a backup copy of the lpReplacedFileName file. If this parameter is NULL, no backup file is created.
dwReplaceFlags
[in] Specifies how the file is to be replaced. This parameter can be one or more of the following values.
Value | Meaning
REPLACEFILE_WRITE_THROUGH | Guarantees that information copied from the replaced file is flushed to disk before the function returns.
REPLACEFILE_IGNORE_MERGE_ERRORS | Ignores errors that occur while merging information from the replaced file to the replacement file.

lpExclude
Reserved for future use.
lpReserved
Reserved for future use.

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. GetLastError may return one of the following error codes that are specific to this function.

Error Code | Meaning
ERROR_UNABLE_TO_REMOVE_REPLACED | The replaced file could not be deleted. The replaced and replacement files retain their original file names.
ERROR_UNABLE_TO_MOVE_REPLACEMENT | The replacement file could not be renamed. If lpBackupFileName was specified, the replaced and replacement files retain their original file names. Otherwise, the replaced file no longer exists and the replacement file exists under its original name.
ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 | The replacement file could not be renamed. The replacement file still exists with its original name, but the replaced file exists with the name specified by lpBackupFileName. This error occurs only if lpBackupFileName is not NULL.

If any other error is returned, such as ERROR_INVALID_PARAMETER, the replaced and replacement files will retain their original file names.

Remarks

The ReplaceFile function combines several of steps into a single function. An application can call ReplaceFile instead of calling separate functions to save the data to a new file, rename the original file using a temporary name, rename the new file to have the same name as the original file, and delete the original file. Another advantage is that ReplaceFile not only copies the new file data, but also preserves the following attributes of the original file:

  • Creation time
  • Last write time
  • Short file name
  • Object identifier
  • DACLs
  • Encryption
  • Compression
  • Named streams not already in the replacement file

For example, if the replacement file is encrypted, but the replaced file is not encrypted, the resulting file is not encrypted.

The backup file, replaced file, and replacement file must all reside on the same volume.

To delete or rename a file, you must have either delete permission on the file or delete child permission in the parent directory. If you set up a directory with all access except delete and delete child and the DACLs of new files are inherited, then you should be able to create a file without being able to delete it. However, you can then create a file, and you will get all the access you request on the handle returned to you at the time you create the file. If you requested delete permission at the time you created the file, you could delete or rename the file with that handle but not with any other.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File I/O Overview, File I/O Functions, CopyFile, CopyFileEx, MoveFile, MoveFileEx, MoveFileWithProgress


SearchPath

The SearchPath function searches for the specified file.

DWORD SearchPath(
  LPCTSTR lpPath,      // search path
  LPCTSTR lpFileName,  // file name
  LPCTSTR lpExtension, // file extension
  DWORD nBufferLength, // size of buffer
  LPTSTR lpBuffer,     // found file name buffer
  LPTSTR *lpFilePart   // file component
);

Parameters

lpPath
[in] Pointer to a null-terminated string that specifies the path to be searched for the file. If this parameter is NULL, the function searches for a matching file in the following directories in the following sequence:
  1. The directory from which the application loaded.
  2. The current directory.
  3. Windows 95/98/Me: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.

    Windows NT/2000 or later: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.

  4. Windows NT/2000 or later: The 16-bit Windows system directory. There is no function that retrieves the path of this directory, but it is searched. The name of this directory is SYSTEM.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the file to search for.
lpExtension
[in] Pointer to a null-terminated string that specifies an extension to be added to the file name when searching for the file. The first character of the file name extension must be a period (.). The extension is added only if the specified file name does not end with an extension.

If a file name extension is not required or if the file name contains an extension, this parameter can be NULL.

nBufferLength
[in] Specifies the length, in TCHARs, of the buffer that receives the valid path and file name.
lpBuffer
[out] Pointer to the buffer that receives the path and file name of the file found.
lpFilePart
[out] Pointer to the variable that receives the address (within lpBuffer) of the last component of the valid path and file name, which is the address of the character immediately following the final backslash (\) in the path.

Return Values

If the function succeeds, the value returned is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character. If the return value is greater than nBufferLength, the value returned is the size of the buffer required to hold the path.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, FindFirstFile, FindNextFile, GetSystemDirectory, GetWindowsDirectory


SetCurrentDirectory

The SetCurrentDirectory function changes the current directory for the current process.

BOOL SetCurrentDirectory(
  LPCTSTR lpPathName   // new directory name
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the path to the new current directory. This parameter may be a relative path or a full path. In either case, the full path of the specified directory is calculated and stored as the current directory.

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

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

Each process has a single current directory made up of two parts:

  • A disk designator that is either a drive letter followed by a colon, or a server name and share name (\\servername\sharename)
  • A directory on the disk designator

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetCurrentDirectory


SetEndOfFile

The SetEndOfFile function moves the end-of-file (EOF) position for the specified file to the current position of the file pointer.

BOOL SetEndOfFile(
  HANDLE hFile   // handle to file
);

Parameters

hFile
[in] Handle to the file to have its EOF position moved. The file handle must have been created with GENERIC_WRITE access to the file.

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

This function can be used to truncate or extend a file. If the file is extended, the contents of the file between the old EOF position and the new position are not defined.

If you called CreateFileMapping to create a file-mapping object for hFile, you must first call UnmapViewOfFile to unmap all views and call CloseHandle to close the file-mapping object before you can call SetEndOfFile.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CloseHandle, CreateFile, CreateFileMapping, UnmapViewOfFile


SetFileApisToANSI

The SetFileApisToANSI function causes the file I/O functions to use the ANSI character set code page. This function is useful for 8-bit console input and output operations.

VOID SetFileApisToANSI(VOID);

Parameters

This function has no parameters.

Return Values

This function has no return value.

Remarks

The file I/O functions whose code page is set by SetFileApisToANSI are those functions exported by KERNEL32.DLL that accept or return a file name. SetFileApisToANSI sets the code page per process, rather than per thread or per computer.

The SetFileApisToANSI function complements the SetFileApisToOEM function, which causes the same set of file I/O functions to use the OEM character set code page.

The 8-bit console functions use the OEM code page by default. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by other functions, and vice versa. For example, if the FindFirstFileA function returns a string that contains certain extended ANSI characters, and the 8-bit console functions are set to use the OEM code page, then the WriteConsoleA function does not display the string properly.

Use the AreFileApisANSI function to determine which code page the set of file I/O functions is currently using. Use the SetConsoleCP and SetConsoleOutputCP functions to set the code page for the 8-bit console functions.

To solve the problem of code page incompatibility, it is best to use Unicode for console applications. Console applications that use Unicode are much more versatile than those that use 8-bit console functions. Barring that solution, a console application can call the SetFileApisToOEM function to cause the set of file I/O functions to use OEM character set strings rather than ANSI character set strings. Use the SetFileApisToANSI function to set those functions back to the ANSI code page.

When dealing with command lines, a console application should obtain the command line in Unicode form and then convert it to OEM form using the relevant character-to-OEM functions. Note also that the array in the argv parameter of the command-line main function contains ANSI character set strings in this case.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, AreFileApisANSI, FindFirstFileA, SetFileApisToOEM, SetConsoleCP, SetConsoleOutputCP, WriteConsoleA


SetFileApisToOEM

The SetFileApisToOEM function causes the file I/O functions to use the OEM character set code page. This function is useful for 8-bit console input and output operations.

VOID SetFileApisToOEM(VOID);

Parameters

This function has no parameters.

Return Values

This function has no return value.

Remarks

The file I/O functions whose code page is set by SetFileApisToOEM are those functions exported by KERNEL32.DLL that accept or return a file name. SetFileApisToOEM sets the code page per process, rather than per thread or per computer.

The SetFileApisToOEM function is complemented by the SetFileApisToANSI function, which causes the same set of file I/O functions to use the ANSI character set code page.

The 8-bit console functions use the OEM code page by default. All other functions use the ANSI code page by default. This means that strings returned by the console functions may not be processed correctly by other functions, and vice versa. For example, if the FindFirstFileA function returns a string that contains certain extended ANSI characters, and the 8-bit console functions are set to use the OEM code page, then the WriteConsoleA function will not display the string properly.

Use the AreFileApisANSI function to determine which code page the set of file I/O functions is currently using. Use the SetConsoleCP and SetConsoleOutputCP functions to set the code page for the 8-bit console functions.

To solve the problem of code page incompatibility, it is best to use Unicode for console applications. Console applications that use Unicode are much more versatile than those that use 8-bit console functions. Barring that solution, a console application can call the SetFileApisToOEM function to cause the set of file I/O functions to use OEM character set strings rather than ANSI character set strings. Use the SetFileApisToANSI function to set those functions back to the ANSI code page.

When dealing with command lines, a console application should obtain the command line in Unicode form and then convert it to OEM form using the relevant character-to-OEM functions. Note also that the array in the argv parameter of the command-line main function contains ANSI character set strings in this case.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, AreFileApisANSI, FindFirstFileA, SetConsoleCP, SetConsoleCP, SetConsoleOutputCP, SetFileApisToANSI, WriteConsoleA


SetFileAttributes

The SetFileAttributes function sets a file's attributes.

BOOL SetFileAttributes(
  LPCTSTR lpFileName,      // file name
  DWORD dwFileAttributes   // attributes
);

Parameters

lpFileName
[in] Pointer to a string that specifies the name of the file whose attributes are to be set.

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

dwFileAttributes
[in] Specifies the file attributes to set for the file. This parameter can be one or more of the following values. However, all other values override FILE_ATTRIBUTE_NORMAL.
Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_HIDDEN | The file is hidden. It is not 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 the operating system or is used exclusively by it.
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.

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

The following table describes how to set the attributes that cannot be set using SetFileAttributes.

Attribute | How to Set
FILE_ATTRIBUTE_COMPRESSED | To set a file's compression state, use the DeviceIoControl function with the FSCTL_SET_COMPRESSION operation.
FILE_ATTRIBUTE_DEVICE | Reserved; do not use.
FILE_ATTRIBUTE_DIRECTORY | Files cannot be converted into directories. To create a directory, use the CreateDirectory or CreateDirectoryEx function.
FILE_ATTRIBUTE_ENCRYPTED | To create an encrypted file, use the CreateFile function with the FILE_ATTRIBUTE_ENCRYPTED attribute. To convert an existing file into an encrypted file, use the EncryptFile function.
FILE_ATTRIBUTE_REPARSE_POINT | To associate a reparse point with a file, use the DeviceIoControl function with the FSCTL_SET_REPARSE_POINT operation.
FILE_ATTRIBUTE_SPARSE_FILE | To set a file's sparse attribute, use the DeviceIoControl function with the FSCTL_SET_SPARSE operation.

For example, see Searching for Files and Changing File Attributes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetFileAttributes


SetFilePointer

The SetFilePointer function moves the file pointer of an open file.

This function stores the file pointer in two DWORD values. To more easily work with file pointers that are larger than a single DWORD value, use the SetFilePointerEx function.

DWORD SetFilePointer(
  HANDLE hFile,                // handle to file
  LONG lDistanceToMove,        // bytes to move pointer
  PLONG lpDistanceToMoveHigh,  // bytes to move pointer
  DWORD dwMoveMethod           // starting point
);

Parameters

hFile
[in] Handle to the file whose file pointer is to be moved. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file.
lDistanceToMove
[in] Low-order 32 bits of a signed value that specifies the number of bytes to move the file pointer. If lpDistanceToMoveHigh is not NULL, lpDistanceToMoveHigh and lDistanceToMove form a single 64-bit signed value that specifies the distance to move. If lpDistanceToMoveHigh is NULL, lDistanceToMove is a 32-bit signed value. A positive value for lDistanceToMove moves the file pointer forward in the file, and a negative value moves the file pointer backward.
lpDistanceToMoveHigh
[in] Pointer to the high-order 32 bits of the signed 64-bit distance to move. If you do not need the high-order 32 bits, this pointer may be NULL. When non-NULL, this parameter also receives the high-order DWORD of the new value of the file pointer. For more information, see the Remarks section later in this topic.

Windows 95/98/Me: If the pointer lpDistanceToMoveHigh is not NULL, then it must point to either 0, INVALID_SET_FILE_POINTER, or the sign extension of the value of lDistanceToMove. Any other value will be rejected.

dwMoveMethod
[in] Starting point for the file pointer move. This parameter can be one of the following values.
Value | Meaning
FILE_BEGIN | The starting point is zero or the beginning of the file.
FILE_CURRENT | The starting point is the current value of the file pointer.
FILE_END | The starting point is the current end-of-file position.

Return Values

If the SetFilePointer function succeeds and lpDistanceToMoveHigh is NULL, the return value is the low-order DWORD of the new file pointer. If lpDistanceToMoveHigh is not NULL, the function returns the low order DWORD of the new file pointer, and puts the high-order DWORD of the new file pointer into the LONG pointed to by that parameter.

If the function fails and lpDistanceToMoveHigh is NULL, the return value is INVALID_SET_FILE_POINTER. To get extended error information, call GetLastError.

If the function fails, and lpDistanceToMoveHigh is non-NULL, the return value is INVALID_SET_FILE_POINTER. However, because INVALID_SET_FILE_POINTER is a valid value for the low-order DWORD of the new file pointer, you must check GetLastError to determine whether an error occurred. If an error occurred, GetLastError returns a value other than NO_ERROR. For a code example that illustrates this point, see the Remarks section later in this topic.

If the new file pointer would have been a negative value, the function fails, the file pointer is not moved, and the code returned by GetLastError is ERROR_NEGATIVE_SEEK.

Remarks

You cannot use the SetFilePointer function with a handle to a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

To determine the present position of a file pointer, see Retrieving a File Pointer.

Use caution when setting the file pointer in a multithreaded application. You must synchronize access to shared resources. For example, an application whose threads share a file handle, update the file pointer, and read from the file must protect this sequence by using a critical section object or mutex object. For more information about these objects, see Critical Section Objects and Mutex Objects.

If the hFile file handle was opened with the FILE_FLAG_NO_BUFFERING flag set, an application can move the file pointer only to sector-aligned positions. A sector-aligned position is a position that is a whole number multiple of the volume's sector size. An application can obtain a volume's sector size by calling the GetDiskFreeSpace function. If an application calls SetFilePointer with distance-to-move values that result in a position that is not sector-aligned and a handle that was opened with FILE_FLAG_NO_BUFFERING, the function fails, and GetLastError returns ERROR_INVALID_PARAMETER.

Note that it is not an error to set the file pointer to a position beyond the end of the file. The size of the file does not increase until you call the SetEndOfFile, WriteFile, or WriteFileEx function. A write operation increases the size of the file to the file pointer position plus the size of the buffer written, leaving the intervening bytes uninitialized.

If the return value is INVALID_SET_FILE_POINTER and if lpDistanceToMoveHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded or failed. The following sample code illustrates this point:

// Case One: calling the function with lpDistanceToMoveHigh == NULL

// Try to move hFile's file pointer some distance.
dwPtr = SetFilePointer (hFile, lDistance, NULL, FILE_BEGIN) ;

if (dwPtr == INVALID_SET_FILE_POINTER) // Test for failure
{
    // Obtain the error code.
    dwError = GetLastError() ;

    // Deal with failure.
    // . . .

} // End of error handler

//
// Case Two: calling the function with lpDistanceToMoveHigh != NULL

// Try to move hFile's file pointer some huge distance.
dwPtrLow = SetFilePointer (hFile, lDistLow, & lDistHigh, FILE_BEGIN) ;

// Test for failure
if (dwPtrLow == INVALID_SET_FILE_POINTER && (dwError = GetLastError()) != NO_ERROR )
{
    // Deal with failure.
    // . . .

} // End of error handler

The parameter lpDistanceToMoveHigh is used to manipulate huge files. If it is set to NULL, then lDistanceToMove has a maximum value of 2^31–2, or 2 gigabytes less two. This is because all file pointer values are signed values. Therefore if there is even a small chance that the file will grow to that size, you should treat the file as a huge file and work with 64-bit file pointers. With file compression on NTFS, and sparse files, it is possible to have files that are large even if the underlying volume is not very large.

If lpDistanceToMoveHigh is not NULL, then lpDistanceToMoveHigh and lDistanceToMove form a single 64-bit signed value. The lDistanceToMove parameter is treated as the low-order 32 bits of the value, and lpDistanceToMoveHigh as the upper 32 bits. Thus, lpDistanceToMoveHigh is a sign extension of lDistanceToMove.

To move the file pointer from zero to 2 gigabytes, lpDistanceToMoveHigh can be either NULL or a sign extension of lDistanceToMove. To move the pointer more than 2 gigabytes, use lpDistanceToMoveHigh and lDistanceToMove as a single 64-bit quantity. For example, to move in the range from 2 gigabytes to 4 gigabytes set the contents of lpDistanceToMoveHigh to zero, or to –1 for a negative sign extension of lDistanceToMove.

To work with 64-bit file pointers, you can declare a LONG, treat it as the upper half of the 64-bit file pointer, and pass its address in lpDistanceToMoveHigh. This means you have to treat two different variables as a logical unit, which is error-prone. The problems can be ameliorated by using the LARGE_INTEGER structure to create a 64-bit value and passing the two 32-bit values by means of the appropriate elements of the union.

It is conceptually simpler and better design to use a function to hide the interface to SetFilePointer. To do so, use something like this:

__int64 myFileSeek (HANDLE hf, __int64 distance, DWORD MoveMethod)
{
   LARGE_INTEGER li;

   li.QuadPart = distance;

   li.LowPart = SetFilePointer (hf, li.LowPart, &li.HighPart, MoveMethod);

   if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR)
   {
      li.QuadPart = -1;
   }

   return li.QuadPart;
}

Note You can use SetFilePointer to determine the length of a file. To do this, use FILE_END for dwMoveMethod and seek to location zero. The file offset returned is the length of the file. However, this practice can have unintended side effects, such as failure to save the current file pointer so that the program can return to that location. It is simpler and safer to use GetFileSize instead.

You can also use the SetFilePointer function to query the current file pointer position. To do this, specify a move method of FILE_CURRENT and a distance of zero.

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, GetDiskFreeSpace, GetFileSize, GetFileType, ReadFile, ReadFileEx, SetEndOfFile, SetFilePointerEx, WriteFile, WriteFileEx


SetFilePointerEx

The SetFilePointerEx function moves the file pointer of an open file.

BOOL SetFilePointerEx(
  HANDLE hFile,                    // handle to file
  LARGE_INTEGER liDistanceToMove,  // bytes to move pointer
  PLARGE_INTEGER lpNewFilePointer, // new file pointer
  DWORD dwMoveMethod               // starting point
);

Parameters

hFile
[in] Handle to the file whose file pointer is to be moved. The file handle must have been created with GENERIC_READ or GENERIC_WRITE access to the file.
liDistanceToMove
[in] Specifies the number of bytes to move the file pointer. A positive value moves the pointer forward in the file and a negative value moves the file pointer backward.
lpNewFilePointer
[out] Pointer to a variable that receives the new file pointer. If this parameter is NULL, the new file pointer is not returned.
dwMoveMethod
[in] Specifies the starting point for the file pointer move. This parameter can be one of the following values.
Value | Meaning
FILE_BEGIN | The starting point is zero or the beginning of the file. If this flag is specified, then the liDistanceToMove parameter is interpreted as an unsigned value.
FILE_CURRENT | The start point is the current value of the file pointer.
FILE_END | The starting point is the current end-of-file position.

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

You cannot use the SetFilePointerEx function with a handle to a nonseeking device such as a pipe or a communications device. To determine the file type for hFile, use the GetFileType function.

Use caution when setting the file pointer in a multithreaded application. You must synchronize access to shared resources. For example, an application whose threads share a file handle, update the file pointer, and read from the file must protect this sequence by using a critical section object or a mutex object. For more information about these objects, see Critical Section Objects and Mutex Objects.

If the hFile handle was opened with the FILE_FLAG_NO_BUFFERING flag set, an application can move the file pointer only to sector-aligned positions. A sector-aligned position is a position that is a whole number multiple of the volume's sector size. An application can obtain a volume's sector size by calling the GetDiskFreeSpaceEx function. If an application calls SetFilePointerEx with distance-to-move values that result in a position that is not sector-aligned and a handle that was opened with FILE_FLAG_NO_BUFFERING, the function fails, and GetLastError returns ERROR_INVALID_PARAMETER.

Note that it is not an error to set the file pointer to a position beyond the end of the file. The size of the file does not increase until you call the SetEndOfFile, WriteFile, or WriteFileEx function. A write operation increases the size of the file to the file pointer position plus the size of the buffer written, leaving the intervening bytes uninitialized.

You can use SetFilePointerEx to determine the length of a file. To do this, use FILE_END for dwMoveMethod and seek to location zero. The file offset returned is the length of the file. However, this practice can have unintended side effects, such as failure to save the current file pointer so that the program can return to that location. It is simpler and safer to use the GetFileSizeEx function instead.

You can also use SetFilePointerEx to query the current file pointer position. To do this, specify a move method of FILE_CURRENT and a distance of zero.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, GetDiskFreeSpaceEx, GetFileSizeEx, GetFileType, SetEndOfFile, WriteFile, WriteFileEx


SetFileShortName

[This is preliminary documentation and subject to change.]

The SetFileShortName function sets the short name for the specified file. The file must be on an NTFS volume.

BOOL SetFileShortName(
 HANDLE hFile,
 LPCTSTR lpShortName
);

Parameters

hFile
[in] Handle to the file. The file must have been opened with DELETE access.
lpShortName
[in] Pointer to a string that specifies the short name for the file.

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.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Functions, GetShortPathName


SetFileValidData

[This is preliminary documentation and subject to change.]

The SetFileValidData function sets the valid data length of the specified file. The file must be on an NTFS volume.

BOOL SetFileValidData(
  HANDLE hFile,
  LONGLONG ValidDataLength
);

Parameters

hFile
[in] Handle to the file. The file must have been opened with GENERIC_WRITE access. The file cannot be compressed or sparse.
ValidDataLength
[in] Specifies the new valid data length for the file. This parameter must be a positive value that is greater than the current valid data length, but less than the current file size.

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

The caller must have the SE_MANAGE_VOLUME_NAME privilege.

Applications can find it useful to set a valid data length in the following scenarios:

  • When writing raw clusters directly to disk through a hardware channel. This allows the application to inform the file system that this range contains valid data that can be returned to the user.
  • When creating large files where performance is an issue. This avoids the time it takes to fill the file with zeroes when the file is created or extended.
  • When remotely extending a file and writing to disk on a served-metadata cluster file system.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Functions,


SetVolumeLabel

The SetVolumeLabel function sets the label of a file system volume.

BOOL SetVolumeLabel(
  LPCTSTR lpRootPathName,  // name of volume root directory
  LPCTSTR lpVolumeName     // name for the volume
);

Parameters

lpRootPathName
[in] Pointer to a null-terminated string specifying the root directory of a file system volume. This is the volume the function will label. A trailing backslash is required. If this parameter is NULL, the root of the current directory is used.
lpVolumeName
[in] Pointer to a string specifying a name for the volume. If this parameter is NULL, the function deletes the label from the specified volume.

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.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File I/O Overview, File I/O Functions, GetVolumeInformation


UnlockFile

The UnlockFile function unlocks a region in an open file. Unlocking a region enables other processes to access the region.

For an alternate way to specify the region, use the UnlockFileEx function.

BOOL UnlockFile(
  HANDLE hFile,                    // handle to file
  DWORD dwFileOffsetLow,           // low-order word of start
  DWORD dwFileOffsetHigh,          // high-order word of start
  DWORD nNumberOfBytesToUnlockLow, // low-order word of length
  DWORD nNumberOfBytesToUnlockHigh // high-order word of length
);

Parameters

hFile
[in] Handle to a file that contains a region locked with LockFile. The file handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.
dwFileOffsetLow
[in] Specifies the low-order word of the starting byte offset in the file where the locked region begins.
dwFileOffsetHigh
[in] Specifies the high-order word of the starting byte offset in the file where the locked region begins.

Windows 95/98/Me: dwFileOffsetHigh must be 0, the sign extension of the value of dwFileOffsetLow. Any other value will be rejected.

nNumberOfBytesToUnlockLow
[in] Specifies the low-order word of the length of the byte range to be unlocked.
nNumberOfBytesToUnlockHigh
[in] Specifies the high-order word of the length of the byte range to be unlocked.

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

Unlocking a region of a file releases a previously acquired lock on the file. The region to unlock must correspond exactly to an existing locked region. Two adjacent regions of a file cannot be locked separately and then unlocked using a single region that spans both locked regions.

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the behavior is not specified.

This function works on a file allocation table (FAT) – based file system only if the operating system is running SHARE.EXE.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, LockFile, UnlockFileEx


UnlockFileEx

The UnlockFileEx function unlocks a previously locked byte range in an open file.

BOOL UnlockFileEx(
  HANDLE hFile,                     // handle to file
  DWORD dwReserved,                 // reserved
  DWORD nNumberOfBytesToUnlockLow,  // low-order part of length
  DWORD nNumberOfBytesToUnlockHigh, // high-order part of length
  LPOVERLAPPED lpOverlapped         // unlock region start
);

Parameters

hFile
[in] Handle to a file that is to have an existing locked region unlocked. The handle must have been created with either GENERIC_READ or GENERIC_WRITE access to the file.
dwReserved
Reserved parameter; must be zero.
nNumberOfBytesToUnlockLow
[in] Specifies the low-order part of the length of the byte range to unlock.
nNumberOfBytesToUnlockHigh
[in] Specifies the high-order part of the length of the byte range to unlock.
lpOverlapped
[in] Pointer to an OVERLAPPED structure that the function uses with the unlocking request. This structure contains the file offset of the beginning of the unlock range.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Unlocking a region of a file releases a previously acquired lock on the file. The region to unlock must correspond exactly to an existing locked region. Two adjacent regions of a file cannot be locked separately and then unlocked using a single region that spans both locked regions.

If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the behavior is not specified.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, LockFile, LockFileEx, OVERLAPPED, UnlockFile


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 or later: 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 or later: 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.

Windows NT/2000 or later: 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 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

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

MAPI: For more information, see Syntax and Limitations for Win32 Functions Useful in MAPI Development.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CancelIo, CreateFile, GetLastError, GetOverlappedResult, GetQueuedCompletionStatus, OVERLAPPED, ReadFile, SetEndOfFile, SetErrorMode, WriteFileEx


WriteFileEx

The WriteFileEx function writes data to a file. It is designed solely for asynchronous operation, unlike WriteFile, which is designed for both synchronous and asynchronous operation.

WriteFileEx reports its completion status asynchronously, calling a specified completion routine when writing is completed or canceled and the calling thread is in an alertable wait state.

BOOL WriteFileEx(
  HANDLE hFile,                                       // handle to output file
  LPCVOID lpBuffer,                                   // data buffer
  DWORD nNumberOfBytesToWrite,                        // number of bytes to write
  LPOVERLAPPED lpOverlapped,                          // overlapped buffer
  LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // completion routine
);

Parameters

hFile
[in] Handle to the file to be written to. This file handle must have been created with the FILE_FLAG_OVERLAPPED flag and with GENERIC_WRITE access to the file.

Windows NT/2000 or later: This parameter 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: This parameter 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.

This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

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.

lpOverlapped
[in] Pointer to an OVERLAPPED data structure that supplies data to be used during the overlapped (asynchronous) write operation.

For files that support byte offsets, you must specify a byte offset at which to start writing to the file. You specify this offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. For files that do not support byte offsets, Offset and OffsetHigh are ignored.

The WriteFileEx function ignores the OVERLAPPED structure's hEvent member. An application is free to use that member for its own purposes in the context of a WriteFileEx call. WriteFileEx signals completion of its writing operation by calling, or queuing a call to, the completion routine pointed to by lpCompletionRoutine, so it does not need an event handle.

The WriteFileEx function does use the Internal and InternalHigh members of the OVERLAPPED structure. You should not change the value of these members.

The OVERLAPPED data structure must remain valid for the duration of the write operation. It should not be a variable that can go out of scope while the write operation is pending completion.

lpCompletionRoutine
[in] Pointer to a completion routine to be called when the write operation has been completed and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.

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.

If the WriteFileEx function succeeds, the calling thread has an asynchronous I/O (input/output) operation pending: the overlapped write operation to the file. When this I/O operation finishes, and the calling thread is blocked in an alertable wait state, the operating system calls the function pointed to by lpCompletionRoutine, and the wait completes with a return code of WAIT_IO_COMPLETION.

If the function succeeds and the file-writing operation finishes, but the calling thread is not in an alertable wait state, the system queues the call to *lpCompletionRoutine, holding the call until the calling thread enters an alertable wait state. See Synchronization for more information about alertable wait states and overlapped input/output operations.

Remarks

When using WriteFileEx you should check GetLastError even when the function returns "success" to check for conditions that are "successes" but have some outcome you might want to know about. For example, a buffer overflow when calling WriteFileEx will return TRUE, but GetLastError will report the overflow with ERROR_MORE_DATA. If the function call is successful and there are no warning conditions, GetLastError will return ERROR_SUCCESS.

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 output file is locked by another process, and the specified write operation overlaps the locked portion, the WriteFileEx 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 read from, write to, reallocate, or free the output buffer that a write operation is using until the write operation completes.

The WriteFileEx function may fail, returning the messages ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY if 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.

An application uses the WaitForSingleObjectEx, WaitForMultipleObjectsEx, MsgWaitForMultipleObjectsEx, SignalObjectAndWait, and SleepEx functions to enter an alertable wait state. Refer to Synchronization for more information about alertable wait states and overlapped input/output operations.

Windows 95/98/Me: Neither WriteFileEx nor ReadFileEx can be used by the comm ports to communicate. However, you can use WriteFile and ReadFile to perform asynchronous communication.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CancelIo, CreateFile, FileIOCompletionRoutine, MsgWaitForMultipleObjectsEx, OVERLAPPED, ReadFileEx, SetEndOfFile, SetErrorMode, SleepEx, SignalObjectAndWait, WaitForMultipleObjectsEx, WaitForSingleObjectEx, WriteFile


WriteFileGather

The WriteFileGather function gathers data from a set of buffers and writes the data to a file.

The function starts writing data to the file at a position specified by an OVERLAPPED structure. It operates asynchronously.

BOOL WriteFileGather(
  HANDLE hFile,                          // handle to file
  FILE_SEGMENT_ELEMENT aSegmentArray[ ], // array of buffer pointers
  DWORD nNumberOfBytesToWrite,           // number of bytes to write
  LPDWORD lpReserved,                    // reserved; must be NULL
  LPOVERLAPPED lpOverlapped              // overlapped buffer
);

Parameters

hFile
[in] Handle to the file to write to.

This file handle must have been created using GENERIC_WRITE to specify write access to the file, FILE_FLAG_OVERLAPPED to specify asynchronous I/O, and FILE_FLAG_NO_BUFFERING to specify non-cached I/O.

aSegmentArray
[out] Pointer to an array of FILE_SEGMENT_ELEMENT buffers. The array must contain one member for each system memory page-sized chunk of the total number of bytes to write to the file, plus one member for the final NULL pointer. For example, if the number of bytes to read is 40K, and the system page size is 4K, then this array must have 10 members for data, plus one member for the final NULL member, for a total of 11 members.

Each buffer must be at least the size of a system memory page and must be aligned on a system memory page size boundary. The system will write one system memory page of data from each buffer.

The function gathers the data from the buffers in a sequential manner: it writes data to the file from the first buffer, then from the second buffer, then from the next, until there is no more data to write.

The final element of the array must be a 64-bit NULL pointer.

nNumberOfBytesToWrite
[in] Specifies the total number of bytes to write; each element of aSegmentArray contains a 1-page chunk of this total. Because the file must be opened with FILE_FLAG_NO_BUFFERING, the number of bytes to write must be a multiple of the sector size of the file system on which the file resides.

If nNumberOfBytesToWrite is zero, the function performs a null write operation. The behavior of a null write operation depends on the underlying file system. If nNumberOfBytesToWrite is not zero and the offset and length of the write place data beyond the current end of the file, WriteFileGather will extend the file.

lpReserved
This parameter is reserved for future use. You must set it to NULL.
lpOverlapped
[in] Pointer to an OVERLAPPED data structure.

The WriteFileGather function requires a valid OVERLAPPED structure. The lpOverlapped parameter cannot be NULL.

The WriteFileGather function starts writing data to the file at a position specified by the Offset and OffsetHigh members of the OVERLAPPED structure.

The WriteFileGather function may return before the write operation has completed. In that case, the WriteFileGather function returns the value zero, and the GetLastError function returns the value ERROR_IO_PENDING. This asynchronous operation of WriteFileGather lets the calling process continue while the write operation completes. You can call the GetOverlappedResult, HasOverlappedIoCompleted, or GetQueuedCompletionStatus function to obtain information about the completion of the write operation.

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 the GetLastError function.

If the function returns before the write operation has completed, the function returns zero, and GetLastError returns ERROR_IO_PENDING.

Remarks

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

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP2 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File I/O Overview, File I/O Functions, CreateFile, GetOverlappedResult, GetQueuedCompletionStatus, HasOverlappedIoCompleted, OVERLAPPED, ReadFile, ReadFileEx, ReadFileScatter


File I/O Structures

The following structures are used with file I/O.

BY_HANDLE_FILE_INFORMATION
FILE_NOTIFY_INFORMATION
OFSTRUCT
WIN32_FILE_ATTRIBUTE_DATA
WIN32_FIND_DATA


BY_HANDLE_FILE_INFORMATION

The BY_HANDLE_FILE_INFORMATION structure contains information retrieved by the GetFileInformationByHandle function.

typedef struct _BY_HANDLE_FILE_INFORMATION {
  DWORD    dwFileAttributes;
  FILETIME ftCreationTime;
  FILETIME ftLastAccessTime;
  FILETIME ftLastWriteTime;
  DWORD    dwVolumeSerialNumber;
  DWORD    nFileSizeHigh;
  DWORD    nFileSizeLow;
  DWORD    nNumberOfLinks;
  DWORD    nFileIndexHigh;
  DWORD    nFileIndexLow;
} BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION;

Members

dwFileAttributes
Specifies file attributes. This member can be one or more of the following values.
Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file or directory is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED | The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY | The handle identifies a directory.
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.
FILE_ATTRIBUTE_HIDDEN | The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL | The file has no other attributes. This attribute is valid only if used alone.
FILE_ATTRIBUTE_OFFLINE | The file data 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 or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_REPARSE_POINT | The file has an associated reparse point.
FILE_ATTRIBUTE_SPARSE_FILE | The file is a sparse file.
FILE_ATTRIBUTE_SYSTEM | The file or directory is part of the operating system 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 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.

ftCreationTime
Specifies the time the file was created. If the underlying file system does not support this time member, ftCreationTime is zero.
ftLastAccessTime
Specifies the time the file was last accessed. If the underlying file system does not support this time member, ftLastAccessTime is zero.
ftLastWriteTime
Specifies the last time the file was written to.
dwVolumeSerialNumber
Specifies the serial number of the volume that contains the file.
nFileSizeHigh
Specifies the high-order word of the file size.
nFileSizeLow
Specifies the low-order word of the file size.
nNumberOfLinks
Specifies the number of links to this file. For the FAT file system this member is always 1. For NTFS, it may be more than 1.
nFileIndexHigh
Specifies the high-order word of a unique identifier associated with the file.
nFileIndexLow
Specifies the low-order word of a unique identifier associated with the file. This identifier and the volume serial number uniquely identify a file. An application can use this identifier and the volume serial number to determine whether two handles refer to the same file.

Remarks

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Furthermore, FAT records times on disk in local time, while NTFS records times on disk in UTC, so it is not affected by changes in time zone or daylight saving time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Structures, GetFileInformationByHandle


FILE_NOTIFY_INFORMATION

The FILE_NOTIFY_INFORMATION structure describes the changes found by the ReadDirectoryChangesW function.

typedef struct _FILE_NOTIFY_INFORMATION {
  DWORD NextEntryOffset;
  DWORD Action;
  DWORD FileNameLength;
  WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;

Members

NextEntryOffset
Specifies the number of bytes that must be skipped to get to the next record. A value of zero indicates that this is the last record.
Action
Specifies the type of change that occurred.
Value | Meaning
FILE_ACTION_ADDED | The file was added to the directory.
FILE_ACTION_REMOVED | The file was removed from the directory.
FILE_ACTION_MODIFIED | The file was modified. This can be a change in the time stamp or attributes.
FILE_ACTION_RENAMED_OLD_NAME | The file was renamed and this is the old name.
FILE_ACTION_RENAMED_NEW_NAME | The file was renamed and this is the new name.

FileNameLength
Specifies the length, in bytes, of the file name portion of the record. Note that this length does not include the terminating null character.
FileName
This is a variable-length field that contains the file name relative to the directory handle. The file name is in the Unicode character format and is not null-terminated.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.

See Also

File I/O Overview, File I/O Structures, ReadDirectoryChangesW


OFSTRUCT

The OFSTRUCT structure contains information about a file that the OpenFile function opened or attempted to open.

typedef struct _OFSTRUCT {
  BYTE cBytes;
  BYTE fFixedDisk;
  WORD nErrCode;
  WORD Reserved1;
  WORD Reserved2;
  CHAR szPathName[OFS_MAXPATHNAME];
} OFSTRUCT, *POFSTRUCT;

Members

cBytes
Specifies the length, in bytes, of the structure.
fFixedDisk
Specifies whether the file is on a hard (fixed) disk. This member is nonzero if the file is on a hard disk.
nErrCode
Specifies the MS-DOS error code if the OpenFile function failed.
Reserved1
Reserved; do not use.
Reserved2
Reserved; do not use.
szPathName
Specifies the path and file name of the file.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Structures, OpenFile


WIN32_FILE_ATTRIBUTE_DATA

The WIN32_FILE_ATTRIBUTE_DATA structure contains attribute information for a file or directory. The GetFileAttributesEx function uses this structure.

typedef struct _WIN32_FILE_ATTRIBUTE_DATA{
  DWORD      dwFileAttributes;
  FILETIME   ftCreationTime;
  FILETIME   ftLastAccessTime;
  FILETIME   ftLastWriteTime;
  DWORD      nFileSizeHigh;
  DWORD      nFileSizeLow;
} WIN32_FILE_ATTRIBUTE_DATA, *LPWIN32_FILE_ATTRIBUTE_DATA;

Members

dwFileAttributes
Specifies FAT-style attribute information for the file or directory.

The following attributes are defined.
Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file or directory is an archive file. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED | The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY | The handle identifies a directory.
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.
FILE_ATTRIBUTE_HIDDEN | The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL | The file or directory has no other attributes set. This attribute is valid only if used alone.
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 or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_REPARSE_POINT | The file has an associated reparse point.
FILE_ATTRIBUTE_SPARSE_FILE | The file is a sparse file.
FILE_ATTRIBUTE_SYSTEM | The file or directory is part of the operating system 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.

ftCreationTime
A FILETIME structure that specifies when the file or directory was created.
ftLastAccessTime
A FILETIME structure. For a file, the structure specifies when the file was last read from or written to. For a directory, the structure specifies when the directory was created. For both files and directories, the specified date will be correct, but the time of day will always be set to midnight.
ftLastWriteTime
A FILETIME structure. For a file, the structure specifies when the file was last written to. For a directory, the structure specifies when the directory was created.
nFileSizeHigh
Specifies the high-order DWORD of the file size. This member has no meaning for directories.
nFileSizeLow
Specifies the low-order DWORD of the file size. This member has no meaning for directories.

Remarks

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Furthermore, FAT records times on disk in local time, while NTFS records times on disk in UTC, so it is not affected by changes in time zone or daylight saving time.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Structures, GetFileAttributesEx, GET_FILEEX_INFO_LEVELS


WIN32_FIND_DATA

The WIN32_FIND_DATA structure describes a file found by the FindFirstFile, FindFirstFileEx, or FindNextFile function.

typedef struct _WIN32_FIND_DATA {
  DWORD    dwFileAttributes;
  FILETIME ftCreationTime;
  FILETIME ftLastAccessTime;
  FILETIME ftLastWriteTime;
  DWORD    nFileSizeHigh;
  DWORD    nFileSizeLow;
  DWORD    dwReserved0;
  DWORD    dwReserved1;
  TCHAR    cFileName[ MAX_PATH ];
  TCHAR    cAlternateFileName[ 14 ];
} WIN32_FIND_DATA, *PWIN32_FIND_DATA;

Members

dwFileAttributes
Specifies the file attributes of the file found. This member can be one or more of the following values.
Attribute | Meaning
FILE_ATTRIBUTE_ARCHIVE | The file or directory is an archive file or directory. Applications use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED | The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DIRECTORY | The handle identifies a directory.
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.
FILE_ATTRIBUTE_HIDDEN | The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_NORMAL | The file or directory has no other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_OFFLINE | The file data 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 or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
FILE_ATTRIBUTE_REPARSE_POINT | The file has an associated reparse point.
FILE_ATTRIBUTE_SPARSE_FILE | The file is a sparse file.
FILE_ATTRIBUTE_SYSTEM | The file or directory is part of the operating system 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 it back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed.

ftCreationTime
Specifies a FILETIME structure containing the time the file was created. FindFirstFile and FindNextFile report file times in Coordinated Universal Time (UTC) format. These functions set the FILETIME members to zero if the file system containing the file does not support this time member. You can use the FileTimeToLocalFileTime function to convert from UTC to local time, and then use the FileTimeToSystemTime function to convert the local time to a SYSTEMTIME structure containing individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
ftLastAccessTime
Specifies a FILETIME structure containing the time that the file was last accessed. The time is in UTC format; the FILETIME members are zero if the file system does not support this time member.
ftLastWriteTime
Specifies a FILETIME structure containing the time that the file was last written to. The time is in UTC format; the FILETIME members are zero if the file system does not support this time member.
nFileSizeHigh
Specifies the high-order DWORD value of the file size, in bytes. This value is zero unless the file size is greater than MAXDWORD. The size of the file is equal to (nFileSizeHigh * (MAXDWORD+1)) + nFileSizeLow.
nFileSizeLow
Specifies the low-order DWORD value of the file size, in bytes.
dwReserved0
If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse tag. Otherwise, this value is undefined and should not be used.
dwReserved1
Reserved for future use.
cFileName
A null-terminated string that is the name of the file.
cAlternateFileName
A null-terminated string that is an alternative name for the file. This name is in the classic 8.3 (filename.ext) file name format.

Remarks

If a file has a long file name, the complete name appears in the cFileName field, and the 8.3 format truncated version of the name appears in the cAlternateFileName field. Otherwise, cAlternateFileName is empty. As an alternative, you can use the GetShortPathName function to find the 8.3 format version of a file name.

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Furthermore, FAT records times on disk in local time, while NTFS records times on disk in UTC, so it is not affected by changes in time zone or daylight saving time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

File I/O Overview, File I/O Structures, FILETIME, FindFirstFile, FindFirstFileEx, FindNextFile, FileTimeToLocalFileTime, FileTimeToSystemTime, GetShortPathName


File I/O Enumeration Types

The following enumeration types are used with file I/O.

FINDEX_INFO_LEVELS
FINDEX_SEARCH_OPS
GET_FILEEX_INFO_LEVELS


FINDEX_INFO_LEVELS

The FINDEX_INFO_LEVELS enumeration type defines values that are used with the FindFirstFileEx function to specify the information level of the returned data.

typedef enum _FINDEX_INFO_LEVELS {
  FindExInfoStandard
} FINDEX_INFO_LEVELS ;

Enumeration Values

FindExInfoStandard
The FindFirstFileEx function retrieves a standard set of attribute information. The data is returned in a WIN32_FIND_DATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Enumeration Types, FindFirstFileEx, WIN32_FIND_DATA


FINDEX_SEARCH_OPS

The FINDEX_SEARCH_OPS enumeration type defines values that are used with the FindFirstFileEx function to specify the type of filtering to perform.

typedef enum _FINDEX_SEARCH_OPS {
  FindExSearchNameMatch,
  FindExSearchLimitToDirectories,
  FindExSearchLimitToDevices,
} FINDEX_SEARCH_OPS ;

Enumeration Values

FindExSearchNameMatch
Search for a file that matches the specified file name. Note that lpSearchFilter parameter of FindFirstFileEx must be NULL when this search operation is used.
FindExSearchLimitToDevices
This filtering type is not available.

For information on enumerating devices, see Device Interfaces.

FindExSearchLimitToDirectories
This is an advisory flag.

If the file system supports directory filtering, the function searches for a "file" that matches the specified file name and that is a directory.

If the file system does not support directory filtering, this flag is silently ignored.

The lpSearchFilter parameter of FindFirstFileEx must be NULL when this search operation is used.

If you want directory filtering, use this flag on all file systems, but be sure to examine the file attribute data stored into the *lpFindFileData parameter of FindFirstFileEx to determine whether the function has indeed returned a handle to a directory.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Enumeration Types, FindFirstFileEx


GET_FILEEX_INFO_LEVELS

The GET_FILEEX_INFO_LEVELS enumeration type defines values that are used with the GetFileAttributesEx function to specify the type of attribute information to obtain.

typedef enum _GET_FILEEX_INFO_LEVELS {
  GetFileExInfoStandard
} GET_FILEEX_INFO_LEVELS ;

Enumeration Values

GetFileExInfoStandard
The GetFileAttributesEx function retrieves a standard set of attribute information. The data is returned in a WIN32_FILE_ATTRIBUTE_DATA structure.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

File I/O Overview, File I/O Enumeration Types, GetFileAttributesEx, WIN32_FILE_ATTRIBUTE_DATA


File Systems

Win32-based applications rely on file systems to store and retrieve information on mass storage devices. File systems provide the underlying support that applications need to create and access files and directories on the individual volumes associated with the devices.

Each file system consists of one or more drivers and supporting dynamic-link libraries that define the data formats and features of the file system. These determine the conventions used for file names, the level of security and recoverability available, and the general performance of input and output (I/O) operations.

  • About File Systems
  • Using File System Features
  • File System Reference


About File Systems

Depending on the configuration of a computer, a Win32®-based application may have access to volumes managed by any of the following file systems: NTFS, FAT, or protected-mode FAT. Because the different volumes your application connects to can be managed by different file systems, it is important to understand the differences between file systems and to prepare your application to work effectively with all file systems.

Note Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT® FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, the GetFileTime function may not return the same file time information set using the SetFileTime function. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC, so it is not affected by changes in time zone or daylight saving time.

Before you access files and directories on a given volume, you should determine the capabilities of the file system by using the GetVolumeInformation function. This function returns values that you can use to adapt your application to work effectively with the file system.

In general, you should avoid using static buffers for file names and paths. Instead, use the values returned by GetVolumeInformation to allocate buffers as you need them. If you must use static buffers, reserve 256 characters for file names and 260 characters for paths.

This overview describes the following:

  • Shared File System Features
  • NTFS File System
  • FAT File System
  • Protected-Mode FAT File System


Shared File System Features

This section describes features common to both the NTFS and File Allocation Table (FAT) file systems:

  • Opportunistic Locks


Opportunistic Locks

An opportunistic lock (also called an oplock) is a lock placed by a client on a file residing on a server. In most cases, a client requests an opportunistic lock so it can cache data locally, thus reducing network traffic and improving apparent response time. Opportunistic locks are used by network redirectors on clients with remote servers, as well as by client applications on local servers.

Opportunistic locks coordinate data caching and coherency between clients and servers and among multiple clients. Data that is coherent is data that is the same across the network. In other words, if data is coherent, data on the server and all the clients is synchronized.

Opportunistic locks are not commands by the client to the server. They are requests from the client to the server. From the point of view of the client, they are opportunistic. In other words, the server grants such locks whenever other factors make the locks possible.

When a local application requests access to a remote file, the implementation of opportunistic locks is transparent to the application. The network redirector and the server involved open and close the opportunistic locks automatically. However, opportunistic locks can also be used when a local application requests access to a local file, and access by other applications and processes must be delegated to prevent corruption of the file. In this case, the local application directly requests an opportunistic lock from the local file system and caches the file locally. When used in this way, the opportunistic lock is effectively a semaphore managed by the local server, and is mainly used for the purposes of data coherency in the file and file access notification. Refer to How to Request an Opportunistic Lock for more information on how to directly request an opportunistic lock.

Local applications should not attempt to request opportunistic locks from remote servers. An error will be returned by DeviceIoControl if an attempt is made to do this.

Opportunistic locks and the associated operations implemented in the Microsoft® Windows® 2000 operating system are a superset of the opportunistic lock portion of the Common Internet File System (CIFS) protocol, an Internet Draft. The CIFS protocol is an enhanced version of the Server Message Block (SMB) protocol. For more information on the CIFS protocol, see Common Internet File System Protocol in the Networking Services section of the Platform Software Development Kit (SDK).

Note that the CIFS Internet Draft explicitly provides that a CIFS implementation may implement opportunistic locks by refusing to grant them.

For additional information on opportunistic locks, see the CIFS Internet Draft discussion on the topic.

Any discrepancies between this discussion and the current CIFS Internet Draft should be resolved in favor of the Internet Draft.


Alternatives to Opportunistic Lock Operations

The following operations are of very limited use to Win32®-based applications. Probably the only practical use for these operations at the Win32 level is to test a network redirector or a server opportunistic lock handler.

Typically, file systems implement support for opportunistic locks. Applications generally leave opportunistic lock management to the file system drivers. Anyone implementing a file system for Windows 2000 should use the Installable File System (IFS) Kit for Windows 2000.

Anyone developing a device driver other than an installable file system should use the Windows 2000 Driver Development Kit (DDK).


Local Caching

Local caching of data is a technique used to speed network access to data files. It involves caching data on clients rather than on servers when possible.

The effect of local caching is that it allows multiple write operations on the same region of a file to be combined into one write operation across the network. Local caching reduces network traffic because the data is written once. Such caching improves the apparent response time of applications because the applications do not wait for the data to be sent across the network to the server.

Local caching of data to be read can appear to speed things up by means of reading ahead. A simple example is an application accessing data sequentially, such as a compiler's preprocessor. In such cases, the network layer of the operating system reads data across the network before the application requests the data. Ideally, the network delivers the data before the application requests it from the file system, resulting in near-instantaneous response. In practice, this rarely happens, but often reading ahead speeds applications by anticipating the next request.

Local caching can also help reduce network traffic by reading a portion of a file across the network once and then keeping it in the local cache. Subsequent read operations on that portion by the application read from the local cache.

One type of application that can benefit from local caching is batch files. Command processors such as the Command.com command processor in Microsoft® Windows® 95 read and execute a batch file one line at a time. For each line, the command processor opens the file, searches to the beginning of the line, reads as much as it needs, closes the file, then executes the line. Each line results in a lot of network traffic. Network traffic can be reduced considerably by caching the entire batch file on a client.

Local caching also helps with another problem associated with networks, especially networks that perform work over modems and other thin pipes: slow response time. Users do not want to wait while data is retrieved over the network, modified, and then written back. With reading ahead and write caching, it often appears that these functions operate much faster than they actually do.

A hazard of local caching is that written data only has as much integrity as the client itself for as long as the data is cached on the client. In general, locally cached data should be flushed to the server as soon as possible. With modern operating systems and hardware support such as uninterruptible power supplies, the risk of losing locally cached data is reduced. But the risk still exists, and you should consider both the trade-off between data integrity and apparent response speed and the trade-off between data integrity and reduced network traffic.


Data Coherency

Data that is coherent is data that is the same across the network. In other words, if data is coherent, data on the server and all the clients is synchronized. One type of software system that provides data coherency is a revision control system (RCS). Such a system is usually fairly simple, with only one user allowed to modify a specified file at a time. Others can read the file but cannot change it.

The user who can change a file is said to have checked it out. The user then checks in the modified file so that others may see the changes. Only after the user has checked a file back in can another user check it out.

An RCS requires the active intervention of users to operate in a useful manner. A file system that operates across a network should handle the problem automatically.

Providing local caching of coherent data is fairly simple when you have one thread on one client accessing a file across the network at a time. However, in most situations many different threads on one or more computers may be reading the same file. This situation is still fairly straightforward. Because the data in the file is static, each client computer can have its own local copy with no implications for data coherency.

A more common situation is one thread modifying the file, and a lot of other threads reading it. The moment a write operation occurs, all of the local caches of that file are obsolete. The server must notify each client to abandon its cache. Any subsequent read operations for the file must be performed across the network.

In another common situation, multiple threads on one or more network clients might try to write to the same file. This situation is similar to a one in which several RCS users all want to make changes to the same file. Each user in sequence must check out the file, make changes, and then check the file back in. Similarly, in a local caching scheme the server must hand off the privilege of writing to a file to one client thread at a time.


How to Request an Opportunistic Lock

Client applications directly request opportunistic locks only when the lock is intended for a file on the local server. When accessing files on remote servers, it is the network redirector, and not the client application, that requests the opportunistic lock from the remote server.

Opportunistic locks are requested by first opening a file with permissions and flags appropriate to the application opening the file. All files for which opportunistic locks will be requested must be opened for overlapped (asynchronous) operation. After the files are opened for overlapped operation, use the DeviceIoControl function with the appropriate operation to request an opportunistic lock. For a list of the opportunistic lock operations, see Opportunistic Lock Operations.

Applications are notified that an opportunistic lock is broken by using the hEvent member of the OVERLAPPED structure associated with the file. Applications may also use functions such as GetOverlappedResult and HasOverlappedIoCompleted. The application is responsible for associating the correct file with the broken opportunistic lock.

For more information on notification, see Synchronization.


Server Response to Open Requests on Locked Files

The life of an opportunistic lock includes three distinct time spans. During each, the server determines by different means its reaction to a request from a client to open a file locked by another client. In general, you can minimize the impact your application has on other clients and the impact they have on your application by granting as much sharing as possible, requesting the minimum access level necessary, and using the least intrusive opportunistic lock suitable for your application.

First is the period after the server opens a file for a client but before it grants a lock. During this time, no lock exists on the file, and the server depends on sharing, access modes, and the type of opportunistic lock you request to determine its reaction to another request to open the same file. For example, if you open the file in question for write access, you may inhibit granting opportunistic locks that allow read caching access to other clients. The time span before the server grants a lock is typically in the millisecond range but may be longer.

After the opportunistic lock is granted, the server examines the lock to determine server reaction to an open request on a locked file. Again, how your application opened the file and the type of lock it holds affects how the server responds. For more information on how the server responds in each case, see Types of Opportunistic Locks.

Finally, there is the span after the server determines that your lock should be broken (ended) but before your application completes its reaction to the break. Depending on the type of lock, your application can downgrade the lock to a lower level or to none at all. Your application can also close the file and the lock. During this time, the server holds in abeyance any requests from other clients to open the formerly locked file. This time span may range from milliseconds to tens of seconds. For more information, see Breaking Opportunistic Locks.


Types of Opportunistic Locks

The opportunistic lock operations work with four types of opportunistic locks: level 1, level 2, batch, and filter. Exclusive opportunistic locks are level 1, batch, and filter locks. If a thread has any type of exclusive lock on a file, it cannot also have a level 2 lock on the same file.

Level 1 Opportunistic Locks

A level 1 opportunistic lock on a file allows a client to read ahead in the file and cache both read-ahead and write data from the file locally. As long as the client has sole access to a file, there is no danger to data coherency in providing a level 1 opportunistic lock.

The client can request a level 1 opportunistic lock after opening a file. If no other client (or no other thread on the same client) has the file open, the server may grant the opportunistic lock. The client can then cache read and write data from the file locally. If another client has opened the file, then the server refuses the opportunistic lock and the client does no local caching. (The server may refuse the opportunistic lock for other reasons as well, such as not supporting opportunistic locks.)

When the server opens a file that already has a level 1 opportunistic lock on it, the server examines the sharing state of the file before it breaks the level 1 opportunistic lock. If the server breaks the lock after this examination, the time the client with the former lock spends flushing its write cache is time the client requesting the file must wait. This time expenditure means that level 1 opportunistic locks should be avoided on files that many clients open.

However, because the server checks the sharing state before it breaks the lock, in the case where the server would deny an open request due to a sharing conflict the server does not break the lock. For example, if you have opened a file, denied sharing for write operations, and obtained a level 1 lock, the server denies another client's request to open the file for writing before it even examines your lock on the file. In this instance, your opportunistic lock is not broken.

For an example of how a level 1 opportunistic lock works, see Level 1 Opportunistic Lock Example. For more information on breaking opportunistic locks, see Breaking Opportunistic Locks.

Level 2 Opportunistic Locks

A level 2 opportunistic lock informs a client that there are multiple concurrent clients of a file and that none has yet modified it. This lock allows the client to perform read operations and obtain file attributes using cached or read-ahead local information, but the client must send all other requests (such as for write operations) to the server. Your application should use the level 2 opportunistic lock when you expect other applications to write to the file at random or read the file at random or sequentially.

A level 2 opportunistic lock is very similar to a filter opportunistic lock. In most situations, your application should use the level 2 opportunistic lock. Only use the filter lock if you do not want open operations for reading to cause sharing-mode violations in the time span between your application's opening the file and receiving the lock. For more information, see Filter Opportunistic Locks and Server Response to Open Requests on Locked Files.

For more information on breaking opportunistic locks, see Breaking Opportunistic Locks.

Batch Opportunistic Locks

A batch opportunistic lock manipulates file openings and closings. For example, in the execution of a batch file, the batch file may be opened and closed once for each line of the file. A batch opportunistic lock opens the batch file on the server and keeps it open. As the command processor "opens" and "closes" the batch file, the network redirector intercepts the open and close commands. All the server receives are the seek and read commands. If the client is also reading ahead, the server receives a particular read request at most one time.

When opening a file that already has a batch opportunistic lock, the server checks the sharing state of the file after breaking the lock. This check gives the holder of the lock a chance to complete flushing its cache and to close the file handle. An open operation attempted during the sharing check does not cause the sharing check to fail if the lock holder releases the lock.

For an example of how a batch opportunistic lock works, see Batch Opportunistic Lock Example. For more information on breaking opportunistic locks, see Breaking Opportunistic Locks.

Filter Opportunistic Locks

A filter opportunistic lock locks a file so that it cannot be opened for either write or delete access. All clients must be able to share the file. Filter locks allow applications to perform nonintrusive filtering operations on file data (for example, a compiler opening source code or a cataloging program).

A filter opportunistic lock differs from a level 2 opportunistic lock in that it allows open operations for reading to occur without sharing-mode violations in the time span between your application's opening the file and receiving the lock. The filter opportunistic lock is the best lock to use when it is important to allow other clients reading access. In other cases, your application should use a level 2 opportunistic lock. A filter opportunistic lock differs from a batch opportunistic lock in that it does not allow multiple openings and closings to be handled by the network redirector the way a batch opportunistic lock does.

Your application should request a filter opportunistic lock on a file in three steps:

  1. Use the CreateFile function to open a handle to the file with the DesiredAccess parameter set to zero, indicating no access, and the dwShareMode parameter set to the FILE_SHARE_READ flag to allow sharing for reading. The handle obtained at this point is called the locking handle.
  2. Request a lock on this handle with the DeviceIoControl operation FSCTL_REQUEST_FILTER_OPLOCK.
  3. When the lock is granted, use CreateFile to open the file again with DesiredAccess set to the GENERIC_READ flag if you want read access, the GENERIC_WRITE flag if you want write access, or both. Set dwShareMode to the FILE_SHARE_READ flag to allow others to read the file while you have it open, the FILE_SHARE_DELETE flag to allow others to mark the file for deletion while you have it open, or both. The handle obtained at this point is called the read handle.

Use the read handle to read from or write to the contents of the file.

When opening a file that already has a filter opportunistic lock, the server breaks the lock and then checks the sharing state of the file. This check gives the client that held the former opportunistic lock a chance to abandon any cached data and acknowledge the break. An open operation attempted during this sharing check does not cause the sharing check to fail if the former lock holder releases the lock. The file system holds in abeyance the open operation until the lock's owner closes both the read handle and then the locking handle. After this is done, the other client's open request can proceed.

For more information on breaking opportunistic locks, see Breaking Opportunistic Locks.


Breaking Opportunistic Locks

Breaking an opportunistic lock is the process of degrading the lock that one client has on a file so that another client can open the file, with or without an opportunistic lock. When the other client requests the open operation, the server delays the open operation and notifies the client holding the opportunistic lock.

The client holding the lock then takes actions appropriate to the type of lock, for example abandoning read buffers, closing the file, and so on. Only when the client holding the opportunistic lock notifies the server that it is done does the server open the file for the client requesting the open operation. However, when a level 2 lock is broken, the server reports to the client that it has been broken but does not wait for any acknowledgment, as there is no cached data to be flushed to the server.

In acknowledging a break of any exclusive lock (filter, level 1, or batch), the holder of a broken lock cannot request another exclusive lock. It can degrade an exclusive lock to a level 2 lock or no lock at all. The holder typically releases the lock and closes the file when it is about to close the file anyway.

Applications are notified that an opportunistic lock is broken by using the hEvent member of the OVERLAPPED structure associated with the file on which the lock is broken. Applications may also use functions such as GetOverlappedResult and HasOverlappedIoCompleted.


Opportunistic Lock Examples

The following examples show data and SMB message movements as opportunistic locks are made and broken. Note that clients can cache file attribute data as well as file data.

Also note that these examples are based on situations where client applications are requesting opportunistic locks from remote servers. These processes are automatically initiated by the network redirector and the remote server—there is no direct involvement by the client application or applications. The processes described by these examples can be generalized into situations where local client applications are directly requesting opportunistic locks from the local file system, with the exception that no exchange of data over the network is involved.

Level 1 Opportunistic Lock

The following diagram shows a network-traffic view of a level 1 opportunistic lock on a file. The arrows indicate the direction of data movement, if any.

Event | Client X | Server | Client Y
1 | Opens file, requests level 1 lock à |  |
2 |  | ß Grants level 1 opportunistic lock |
3 | Performs read, write, and other operations à |  |
4 |  |  | ß Requests to open file
5 |  | ß Breaks opportunistic lock |
6 | Discards read-ahead data |  |
7 | Writes data à |  |
8 | Sends "close" or "done" message à |  |
9 |  | Okays open operation à |
10 | Performs read, write, and other operations à |  | ß Performs read, write, and other operations

In event 1, client X opens a file and as part of the open operation requests a level 1 opportunistic lock on the file. In event 2, the server grants the level 1 lock because no other client has the file open. The client proceeds to access the file in the usual manner in event 3.

In event 4, client Y attempts to open the file and requests an opportunistic lock. The server sees that client X has the file open. The server ignores Y's request while client X flushes any write data and abandons its read cache for the file.

The server forces X to clean up by sending to X an SMB message breaking the opportunistic lock, event 5. Client X "silently" discards any read-ahead data; in other words, this process generates no network traffic. In event 7, client X writes any cached write data to the server. When client X is done writing cached data to the server, client X sends either a "close" or a "done" message to the server, event 8.

After the server has been notified that client X is done flushing its write cache to the server or has closed the file, then the server can open the file for client Y, in event 9. Because the server now has two clients with the same file open, it grants an opportunistic lock to neither. Both clients proceed to read from the file, and one or neither writes to the file.

Batch Opportunistic Lock

The following diagram shows a network-traffic view of a batch opportunistic lock. The arrows indicate the direction of data movement, if any.

Event | Client X | Server | Client Y
1 | Opens file, requests batch lock à |  |
2 |  | ß Grants batch opportunistic lock |
3 | Reads file à |  |
4 |  | ß Sends data |
5 | Closes file |  |
6 | Opens file |  |
7 | Searches for data |  |
8 | Reads data à |  |
9 |  | ß Sends data |
10 | Closes file |  |
11 |  |  | ß Opens file
12 |  | ß Breaks opportunistic lock |
13 | Closes file à |  |
14 |  | Okays open operation à |
15 |  |  | ß Performs read, write, and other operations

In the batch opportunistic lock, client X opens a file, event 1, and the server grants client X a batch lock in event 2. Client X attempts to read data, event 3, to which the server responds with data, event 4.

Event 5 shows the batch opportunistic lock at work. The application on Client X closes the file. However, the network redirector filters out the close operation and does not transmit a close message, thus performing a "silent" close. The network redirector can do this because client X has sole ownership of the file. Later on, in event 6, the application reopens the file. Again, no data flows across the network. As far as the server is concerned, this client has had the file open since event 2.

Events 7, 8, and 9 show the usual course of network traffic. In event 10, another silent close occurs.

In event 11, client Y attempts to open the file. The server's view of the file is that client X has it open, even though the application on client X has closed it. Therefore, the server sends an a message breaking the opportunistic lock to client X. Client X now sends the close message across the network, event 13. Event 14 follows as the server opens the file for client Y. The application on client X has closed the file, so it does no more transfers to or from the server for that file. Client Y begins data transfers as usual in event 15.

Between the time client X is granted the lock on the file in event 2 and the final close at event 13, any file data that the client has cached is valid, in spite of the intervening application open and close operations. However, after the opportunistic lock is broken, cached data cannot be considered valid.

Filter Opportunistic Lock

The following diagram shows a network-traffic view of a filter opportunistic lock. The arrows indicate the direction of data movement, if any.

Event | Client X | Server | Client Y
1 | Opens file with no access rights à |  |
2 |  | ß Opens the file |
3 | Requests filter lock à |  |
4 |  | ß Grants lock |
5 | Opens file for reading à |  |
6 |  | ß Reopens the file |
7 | Reads data using the read handle à |  |
8 |  | ß Sends data |
9 |  | ß Sends data |
10 |  | ß Sends data |
11 |  |  | ß Opens the file
12 |  | Opens the file à |
13 |  |  | ß Requests filter lock
14 |  | Denies filter lock à |
15 |  |  | ß Reads data
16 |  | Sends data à |
17 | Reads (cached) data |  |
18 | Closes file à |  |
19 |  |  | ß Closes file

In the filter opportunistic lock, client X opens a file, event 1, and the server responds in event 2. The client then requests a filter opportunistic lock in event 3, followed by the server granting the opportunistic lock in event 4. Client X then opens the file again for reading in event 5, to which the server responds in event 6. The client then attempts to read data, to which the server responds with data, event 8.

Event 9 shows the filter opportunistic lock at work. The server reads ahead of the client and sends the data over the network even though the client has not requested it. The client caches the data. In event 10, the server also anticipates a future request for data and sends another portion of the file for the client to cache.

In event 11 and 12, another client, Y, opens the file. Client Y also requests a filter opportunistic lock. In event 14, the server denies it. In event 15, client Y requests data, which the server sends in event 16. None of this affects client X. At any time, another client can open this file for read access. No other client affects client X's filter lock.

Event 17 shows client X reading data. However, because the server has already sent the data and the client has cached it, no traffic crosses the network.

In this example, client X never tries to read all the data in the file, so the read-ahead indicated by events 9 and 10 is "wasted"; that is, the data is never actually used. This is an acceptable loss because the read-ahead has sped up the application.

In event 18, client X closes the file. The client's network redirector abandons the cached data. The server closes the file.


Opportunistic Lock Operations

If a Win32 application requests opportunistic locks, all files for which it requests locks must be opened for overlapped (asynchronous) input and output using the CreateFile function with the FILE_FLAG_OVERLAPPED flag. After the files are opened for overlapped operation, you can use the DeviceIoControl function with one of the operations listed following to work with those files' opportunistic locks.

FSCTL_OPBATCH_ACK_CLOSE_PENDING
FSCTL_OPLOCK_BREAK_ACK_NO_2
FSCTL_OPLOCK_BREAK_ACKNOWLEDGE
FSCTL_OPLOCK_BREAK_NOTIFY
FSCTL_REQUEST_BATCH_OPLOCK
FSCTL_REQUEST_FILTER_OPLOCK
FSCTL_REQUEST_OPLOCK_LEVEL_1
FSCTL_REQUEST_OPLOCK_LEVEL_2


NTFS File System

Microsoft® Windows NT®/Windows® 2000 provides support for the NTFS file system. This file system supports object-oriented applications by treating all files as objects with user- and system-defined attributes. NTFS provides all the capabilities of the FAT file system without many of its limitations. Accessing files under NTFS is often faster than accessing similar files under the FAT file system.

NTFS also includes features not present in FAT, such as security, Unicode file names, automatic creation of MS-DOS® aliases, multiple data streams, and unique functionality specific to the POSIX subsystem. For more information about security, see Access Control. For more information about Unicode, see Unicode and Character Sets.

NTFS file names can be any practical length (up to 255 characters). There is no requirement that NTFS file names have extensions; however, many applications still create and use them. For more information, see File Name Conventions.

The following features are supported on NTFS:

  • File System Recovery
  • File Compression
  • File Encryption
  • Disk Quotas
  • Sparse Files
  • Distributed Link Tracking
  • Reparse Points
  • Volume Mount Points and Mounting Volumes


File System Recovery

NTFS is a fully recoverable file system. It is designed to restore consistency to a disk after a CPU failure, system crash, or I/O error. NTFS allows the operating system to recover without your having to use disk-checking utilities. However, NTFS provides some disk utilities in case recovery fails or corruption occurs outside the control of the file system.


File Compression

Windows NT 3.51 and later support file compression on an individual file basis for NTFS volumes. The following topics discuss NTFS file compression:

  • Compression Attribute
  • Compression State
  • Obtaining the Size of a Compressed File


Compression Attribute

On NTFS volumes, each file and directory has a compression attribute. Other file systems may also implement a compression attribute for individual files and directories.

You can determine whether a file system supports a compression attribute for files and directories by calling the GetVolumeInformation function and examining the FS_FILE_COMPRESSION bit flag.

Use the GetFileAttributes or GetFileAttributesEx function to determine the compression attribute of a file or directory.

If a file's compression attribute is set (FILE_ATTRIBUTE_COMPRESSED), all data in the file is compressed. If the attribute is clear, none of the data in the file is compressed. There is no partially compressed state. The compression attribute is a simple Boolean indicator of compression state.

A directory's compression attribute provides a default compression attribute for newly created files and subdirectories. When you call CreateFile or CreateDirectory to create a new file or directory, the new file or directory inherits the compression attribute of its parent directory.


Compression State

Each file and directory on a volume that supports compression for individual files and directories has a compression state.

Whereas the compression attribute of a file or directory indicates simply whether the file or directory is compressed or not compressed, the compression state also specifies the format of any compressed data.

Use the FSCTL_GET_COMPRESSION DeviceIoControl operation to determine the compression state of a file or directory.

Compression state is encoded as a 16-bit value. A compression state value of COMPRESSION_FORMAT_NONE indicates that a file is not compressed. A value of COMPRESSION_FORMAT_DEFAULT indicates that a file is compressed, using the default compression format. Any other value indicates that a file is compressed, using the compression format specified by the compression state value.

Use the FSCTL_SET_COMPRESSION DeviceIoControl operation to set the compression state of a file or directory. This operation also sets the compression attribute of the file or directory.

Setting the compression state of a file to a nonzero value compresses the file, using the compression format encoded by the compression state value. Setting a file's compression state to zero decompresses the file. These are synchronous operations. The file is compressed or decompressed immediately when you set its compression state.

Setting a directory's compression state does not cause any immediate compression or decompression. Instead, setting a directory's compression state sets a default compression state that will be given to all newly created files and subdirectories.


Obtaining the Size of a Compressed File

Use the GetCompressedFileSize function to obtain the compressed size of a file. If the file is compressed, its compressed size will be less than its uncompressed size. Use the GetFileSize function to determine the uncompressed size of a file.


File Encryption

Windows 2000 supports the Encrypted File System (EFS), which provides cryptographic protection of files on NTFS volumes. EFS provides file encryption on an individual file basis using a public-key system.

Note that EFS encryption and NTFS file compression are mutually exclusive; you cannot compress an encrypted file. Sparse files may be encrypted.

You can determine whether a file system supports file encryption for files and directories by calling the GetVolumeInformation function and examining the FILE_SUPPORTS_ENCRYPTION bit flag. Note that the following items cannot be encrypted:

  • system files
  • system directories
  • root directories

For information on encrypted files, see the following topics:

  • Handling Encrypted Files and Directories
  • Encrypted Files and User Keys

For more information on cryptography in general, see CryptoAPI.


Handling Encrypted Files and Directories

A programmer or user may mark a directory or file as encrypted. A file so marked is encrypted by NTFS using the current encryption driver. If the file is later marked as not encrypted, it is decrypted and left in a plaintext (unsecured) state.

Directories are not themselves encrypted. Rather, by default, in an "encrypted" directory all new files in the directory are encrypted at creation. A user must specifically change the status of a new file to decrypted if the user does not want the file to be encrypted. An encrypted directory is visible. To make a directory inaccessible to other users, use the standard methods of access control.

To encrypt a file, use the CreateFile function with the FILE_ATTRIBUTE_ENCRYPTED flag. To encrypt an existing file, use the EncryptFile function. All data streams in the file are encrypted. If the file is already encrypted, EncryptFile does nothing but return a nonzero value, which indicates success. If the file is compressed, EncryptFile decompresses the file before encrypting it.

To decrypt an encrypted file, use the DecryptFile function. If the file is not encrypted, DecryptFile does nothing but return a nonzero value indicating success.

The EncryptionDisable function disables or enables encryption of the indicated directory and the files in it. It does not affect encryption of subdirectories below the indicated directory.

To retrieve the encryption status of a file, use the FileEncryptionStatus function. Alternatively, call the GetFileAttributes function and examine the FILE_ATTRIBUTE_ENCRYPTED flag in the return value.


Encrypted Files and User Keys

To create a new key for a user, use the SetUserFileEncryptionKey function. To add user keys to an encrypted file, use the AddUsersToEncryptedFile function. To query the user keys for an encrypted file, use the QueryUsersOnEncryptedFile function. To remove user keys from an encrypted file, use the RemoveUsersFromEncryptedFile function.


Disk Quotas

NTFS version 5.0 supports disk quotas, which allow administrators to control the amount of data that each user can store on an NTFS volume. Administrators can optionally configure the system to log an event when users are near their quota, and to deny further disk space to users who exceed their quota. Administrators can also generate reports and use the event monitor to track quota issues.

You can determine whether a file system supports disk quotas by calling the GetVolumeInformation function and examining the FILE_VOLUME_QUOTAS bit flag.

The following topics discuss disk quotas:

  • Disk Quotas and Free Space
  • Disk Quota Limits
  • Disk Quota States
  • Administering Disk Quotas
  • Disk Quota Interfaces


Disk Quotas and Free Space

Disk quotas are transparent to the user. When a user asks how much space is free on a disk, the system reports only the available quota allowance the user has available. If the user exceeds this allowance, the system returns the same error it would return to indicate that the disk was full.

To obtain more free disk space after exceeding the quota allowance, the user must do one of the following:

  • Delete some files.
  • Have another user claim ownership of some files.
  • Have the administrator increase the quota allowance.

Programs that need to retrieve the actual amount of free disk space can call the GetDiskFreeSpaceEx function and look at the TotalNumberOfFreeBytes parameter.


Disk Quota Limits

The disk space used by each file is charged directly to the user who owns the file. The owner of a file is identified by the security identifier (SID) in the security information for the file. The total disk space charged to a user is the sum of the length of all data streams. In other words, property set streams and resident user data streams affect the user's quota. Compressing or decompressing files does not affect the disk space reported for the files. Therefore, quota settings on one volume can be compared to settings on another volume.

The following are the types of disk quota limits:

  • Warning threshold. You can configure the system to generate a system logfile entry when the disk space charged to the user exceeds this value.
  • Hard quota. You can configure the system to generate a system logfile entry when the disk space charged to the user exceeds this value. You can also configure the system to deny additional disk space to the user when the disk space charged to the user exceeds this value.

NTFS automatically creates a user quota entry when a user first writes to the volume. Entries that are created automatically are assigned the default warning threshold and hard quota limit values for the volume.


Disk Quota States

The administrator can turn quota enforcement on and off. There are three quota states, as shown in the following table.

State | Description
Quota disabled | Quota usage changes are not tracked, but the quota limits are not removed. In this state, performance is not affected by disk quotas. This is the default state.
Quota tracked | Quota usage changes are tracked, but quota limits are not enforced. In this state, no quota violation events are generated and no file operations fail because of disk quota violations.
Quota enforced | Quota usage changes are tracked and quota limits are enforced.


Administering Disk Quotas

The administrator can set quotas for specific users on a volume. The administrator can also set default quotas for the volume. A new user on the volume receives the default quota unless the administrator established a quota specifically for that user.

The administrator can query the level of quota tracking, the default quota limits, and the per-user quota information. The per-user quota information contains the user's hard quota limit, warning threshold, and the quota usage.


Disk Quota Interfaces

The following interfaces are used with disk quotas:

  • IDiskQuotaControl
  • IDiskQuotaEvents
  • IDiskQuotaUser
  • IDiskQuotaUserBatch
  • IEnumDiskQuotaUsers


Sparse Files

A file (typically very large) in which a lot of data is all zeros is said to contain a sparse data set. An example is a matrix in which some or much of the data is zeros. Applications that use sparse data sets include image processors and high-speed databases. In versions of NTFS prior to version 5.0, the portions of the file that did not contain useful data occupied valuable disk space.

The file compression introduced in NTFS 3.51 is a partial solution to the problem. The portions of the file that do not contain useful data are set to zero, and file compression compacts the non-data portions. However, file compression has its own drawbacks. Access time may increase due to data compression and decompression.

Windows 2000 NTFS introduces another solution, called a sparse file. When the sparse file facilities are used, the system does not allocate hard drive space to a file except in regions where it contains something other than zeros. The default data value of a sparse file is zero.


Sparse File Operations

You can determine whether a file system supports sparse files by calling the GetVolumeInformation function and examining the FILE_SUPPORTS_SPARSE_FILES bit flag.

Most applications are not aware of sparse files and will not create sparse files. The fact that an application is reading a sparse file is transparent to the application. An application that is aware of sparse-files should determine whether its data set is suitable to be kept in a sparse file. After that determination is made, the application must explicitly declare a file as sparse, using the FSCTL_SET_SPARSE DeviceIoControl operation.

After an application has set a file to be sparse, the application can use the FSCTL_SET_ZERO_DATA DeviceIoControl operation to set a region of the file to zero. In addition, the application can use the FSCTL_QUERY_ALLOCATED_RANGES DeviceIoControl operation to speed searches for nonzero data in the sparse file.

When you perform a write operation (with a function or operation other than FSCTL_SET_ZERO_DATA) whose data consists of nothing but zeros, zeros will be written to the disk for the entire length of the write. To zero out a range of the file and maintain sparseness, use FSCTL_SET_ZERO_DATA.

A sparseness-aware application may also set an existing file to be sparse. If an application sets an existing file to be sparse, it should then scan the file for regions which contain zeros, and use FSCTL_SET_ZERO_DATA to reset those regions, thereby possibly deallocating some physical disk storage. An application upgraded to sparse file awareness should perform this conversion.

When you perform a read operation from a zeroed-out portion of a sparse file, the operating system may not read from the hard drive. Instead, the system recognizes that the portion of the file to be read contains zeros, and it returns a buffer full of zeros without actually reading from the disk.

As with any other file, the system can write data to or read data from any position in a sparse file. Nonzero data being written to a previously zeroed portion of the file may result in allocation of disk space. Zeros being written over nonzero data (only with FSCTL_SET_ZERO_DATA) may result in a deallocation of disk space.

Note It is up to the application to maintain sparseness by writing zeros with FSCTL_SET_ZERO_DATA.

Defragmenting tools that handle compressed files on NTFS file systems will correctly handle sparse files on Windows 2000 NTFS volumes.


Obtaining the Size of a Sparse File

Use the GetCompressedFileSize function to obtain the actual size allocated on disk for a sparse file. This total does not include the size of the regions which were deallocated because they were filled with zeroes. Use the GetFileSize function to determine the total size of a file, including the size of the sparse regions that were deallocated.


Sparse Files and Disk Quota

A sparse file affects user quotas by the nominal size of the file, not the actual allocated amount of disk space. That is, creating a 50-MB file with all zero bytes consumes 50 MB of that user's quota. This means that as the user writes data to the sparse file, he need not worry about exceeding his hard quota limit, because he has already been charged for the space. System administrators should not count on the size of a sparse file remaining small. Therefore they should not grant their users hard quota limits that exceed the physical space available, despite the use of sparse files.


Distributed Link Tracking

Windows 2000 provides the distributed link-tracking service, enabling client applications to track link sources that have been moved. As a result, clients that subscribe to the link-tracking service can maintain the integrity of their references, and the objects referenced can be moved transparently.

A link source is an object referenced by a link client. For example, in a Microsoft® Word document that contains an OLE link to a Microsoft® Excel worksheet, the Word document is the link client and the Excel worksheet is the link source.

The distributed link-tracking service tracks link sources for shell shortcuts and OLE links within NTFS version 5.0 volumes. The link client can mend the broken link with updated information on the new location of the link source.

For more information, see the following topics:

  • Link Tracking Features
  • Link Tracking Components
  • Link Tracking Limitations


Link Tracking Features

Shell shortcuts in Windows 95/98 include heuristic link tracking that uses a tree-search algorithm to find a likely match for a moved link source. The search algorithm is based on the last known path of the file as well as file information that includes the creation date, the file size, and the file name and extension. OLE linking includes the same heuristic link tracking. Windows NT 4.0 also includes the same heuristic link tracking with some added improvements in searching name spaces to yield results in some common scenarios. The improvements include the following steps subject to time limits imposed by the client application:

  1. Search four directory levels down from the last directory.
  2. Move up one directory and repeat steps 1 and 2 another three times which can yield results if the object has been moved nearby.
  3. Search four levels down from the desktop root which can yield results if the object has been moved to a location on the same desktop.
  4. Search four levels down from the root on each local fixed drive.
  5. Repeat steps 1-3 without the four directory limit.

These link-tracking schemes are transparent to the end user. However, they do not always yield positive results and can be time consuming.

Windows 2000 adds a new distributed link tracking service for NTFS. The distributed link-tracking service can be used to track links to files. This service is used by shell shortcuts and by OLE links. See the IShellLink interface for more information on shell shortcuts. See the IOleLink interface for more information on OLE links. If a link is made to a file on an NTFS version 5.0 volume and the file is moved to any other NTFS version 5.0 volume within the same domain, the file will be found by the tracking service, subject to time considerations. Additionally, if the file is moved outside the domain or within a workgroup, it will most likely be found.

When a link is created to a file, the target file is considered the link source and the creator of the link is the link client. For example, if a shell shortcut is created to link to a text document, the text document is the link source and the shell shortcut is the link client.

The distributed link-tracking service maintains file links for the following situations occurring within a domain:

  • The link source file is moved from one NTFS version 5.0 volume to another NTFS version 5.0 volume within the same domain.
  • The name of the machine that holds the link source is renamed.
  • The network shares on the link source machine are changed.
  • The volume holding the link source file is moved to another machine within the same domain.

The distributed link-tracking service also attempts to maintain links in the preceding situations even when they do not occur within a domain, i.e., they are cross-domain or within a workgroup. Links can always be maintained in these situations when the network share on the link source machine is changed. They can also be maintained when a link source is moved within a machine. Links can usually be maintained when the link source is moved to another machine, though this form of tracking is less reliable over time.


Link Tracking Components

This section describes how distributed link tracking is implemented.

Link tracking functionality is primarily implemented in the form of two system services.

Distributed Link Tracking Client
The distributed link tracking client runs on all machines and manages the link-tracking activities for that machine. These activities include searching for link sources and processing link source moves. When a link source is moved, the service passes information to the distributed link tracking server, which runs on domain controllers (DCs).
Distributed Link Tracking Server
The distributed link tracking server runs on each domain controller in a domain. The service accepts notifications of file and volume moves from the tracking service on a computer and allows the distributed link tracking client to query a link source's current location.

This server service maintains information in the DC about volumes and files which have been moved. The information on moves cannot grow above a certain size and it is automatically removed if it becomes unnecessary.

The link tracking services are exposed via the IShellLink and IOleLink interfaces. Thus, they are used by shell shortcuts. When the IShellLink::Resolve method is called and the referent file cannot be found (for example, when the user activates a shell shortcut), the tracking service is called automatically to find the file. Similarly, when the IOleLink implementation cannot find a file, for example in its BindToSource method, it automatically calls on the tracking service.


Link Tracking Limitations

The distributed link-tracking services are available only on Windows 2000, and are only available for link sources on Windows 2000 NTFS volumes. Thus if a link source is moved to a non-Windows 2000 NTFS volume (for example, to a FAT volume), or if a link source is moved to a computer running Windows NT 4.0, the tracking information is lost. Additionally, if a link source is moved even between Windows 2000 NTFS volumes, but the computer performing the move is running an earlier version of Windows NT or Windows 95/98, the link tracking information is lost. When the link tracking information is lost, no harm is done to the link-source file itself, it is simply not trackable by the distributed link-tracking services.

Links to files on removable media are not maintained. Also, the tracking service does not recognize a new NTFS volume until the system is rebooted. A new volume might become available because of repartitioning, reformatting a FAT volume to NTFS, or connecting a new external drive.


Reparse Points

On a Windows 2000 NTFS volume, a file or directory can contain a reparse point, which is a collection of user-defined data. The format of this data is understood by the application which stores the data, and a file system filter, which you install to interpret the data and process the file. When an application sets a reparse point, it stores this data, plus a reparse tag, which uniquely identifies the data it is storing. When the file system opens a file with a reparse point, it attempts to find the file system filter associated with the data format identified by the reparse tag. If such a file system filter is found, the filter processes the file as directed by the reparse data. If no such file system filter is found, the file open operation fails.

For example, reparse points are used to implement NTFS links and the Microsoft Remote Storage Server (RSS). RSS uses an administrator-defined set of rules to move infrequently used files to long term storage, such as tape or CD-ROM. It uses reparse points to store information about the file in the file system. This information is stored in a stub file that contains a reparse point whose data points to the device where the actual file is now located. The file system filter can use this information to retrieve the file.

The following topics discuss reparse points:

  • Reparse Point Tags
  • Reparse Point Operations
  • Reparse Points and File Operations
  • Reparse Point Restrictions


Reparse Point Tags

Each reparse point has an identifier tag so that you can efficiently differentiate between the different types of reparse points, without having to examine the user-defined data in the reparse point. Windows 2000 has a set of predefined tags and a range of tags reserved for Microsoft. If you use any of the reserved tags when setting a reparse point, the operation fails. Tags not included in these ranges are not reserved and are available for your application.

When you set a reparse point, you must tag the data to be placed in the reparse point. After the reparse point has been established, a new set operation fails if the tag for the new data does not match the tag for the existing data. If the tags match, the set operation overwrites the existing reparse point.

To retrieve the reparse point tag, use the FindFirstFile function. If the dwFileAttributes member include the FILE_ATTRIBUTE_REPARSE_POINT attribute, then the dwReserved0 member specifies the reparse point.

Tag Contents

Reparse tags are stored as DWORD values. The bits define certain attributes, as shown in the following diagram.

   3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
   1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
  +-+-+-+-+-----------------------+-------------------------------+
  |M|R|N|R|     Reserved bits     |      Reparse tag value        |
  +-+-+-+-+-----------------------+-------------------------------+

The low 16 bits determine the kind of reparse point. The high 16 bits have 12 bits reserved for future use and 4 bits that denote specific attributes of the tags and the data represented by the reparse point. The following table describes these bits.

Bit | Description
M | Microsoft bit. If this bit is set, the tag is owned by Microsoft. All other tags must use zero for this bit.
R | Reserved; must be zero for all non-Microsoft tags.
N | Name surrogate bit. If this bit is set, the file represents another named entity in the system.

The following macros exist to assist in testing tags:

  • IsReparseTagMicrosoft
  • IsReparseTagNameSurrogate

Each macro returns a nonzero value if the associated bit is set.

The following are Microsoft's predefined reparse tag values:

  • IO_REPARSE_TAG_MOUNT_POINT
  • IO_REPARSE_TAG_HSM
  • IO_REPARSE_TAG_SIS
  • IO_REPARSE_TAG_FILTER_MANAGER

To ensure uniqueness of tags, Microsoft provides a mechanism to distribute new tags. For more information, see the Windows 2000 IFS Kit.


Reparse Point Operations

You can determine whether a file system supports reparse points by calling the GetVolumeInformation function and examining the FILE_SUPPORTS_REPARSE_POINTS bit flag.

You can set, modify, obtain, and remove reparse points by using the DeviceIoControl function. The following table describes the reparse point operations that you can perform using DeviceIoControl.

Operation | Description
FSCTL_SET_REPARSE_POINT | Allows the calling program to set a new reparse point, or to modify an existing one.
FSCTL_GET_REPARSE_POINT | Obtains the information stored in an existing reparse point.
FSCTL_DELETE_REPARSE_POINT | Removes an existing reparse point.

If you are modifying, getting, or deleting a reparse point, you must specify the same reparse tag in the operation that is contained in the file. Otherwise, the operation will fail with the error ERROR_REPARSE_TAG_MISMATCH. If you are modifying or deleting a reparse point, you must also specify the reparse GUID in the operation that is contained in the file. Otherwise, the operation will fail with the error ERROR_REPARSE_ATTRIBUTE_CONFLICT.

To determine whether a file contains a reparse point, use the GetFileAttributes function. If the file has an associated reparse point, the FILE_ATTRIBUTE_REPARSE_POINT attribute is set.

To overwrite an existing reparse point without already having a handle to the file, call CreateFile with FILE_FLAG_OPEN_REPARSE_POINT. This flag allows you to open the file whether or not the corresponding file system filter is installed and working correctly.


Reparse Points and File Operations

Reparse points enable new behavior that you should be aware of when writing applications that manipulate files. For example, backup applications should specify BACKUP_REPARSE_DATA in the WIN32_STREAM_ID structure when backing up files with reparse points. Virus detection applications should search for reparse points that indicate linked files. Most applications should take special actions for files that have been moved to long-term storage, if only to notify the user that it may take a while to retrieve the file.


Reparse Point Restrictions

The following restrictions apply to reparse points:

  • Reparse points can be established for a directory, but the directory must be empty. Otherwise, NTFS fails to establish the reparse point. In addition, you cannot create directories or files in a directory that contains a reparse point.
  • Reparse points and extended attributes are mutually exclusive. NTFS cannot create a reparse point when the file contains extended attributes, and it cannot create extended attributes on a file that contains a reparse point.
  • Reparse point data cannot exceed 16 kilobytes. Setting a reparse point fails if the amount of data to be placed in the reparse point exceeds this limit.


Volume Mount Points and Mounting Volumes

A volume mount point is a directory on a volume that an application can use to "mount" a different volume, that is, to set it up for use at the location a user specifies. In other words, you can use a volume mount point as a gateway to the volume. When a volume is mounted at a volume mount point, users and applications can refer to the mounted volume by the path of the volume mount point or a drive letter. For example, with a volume mount point set the user might refer to drive D as "C:\mnt\Ddrive" as well as "D:".

Using volume mount points, you can unify into one logical file system disparate file systems such as Windows 2000 NTFS, a 16-bit FAT file system, an ISO-9660 file system on a CD-ROM drive, and so on. Neither users nor applications need information about the volume on which a specific file resides. All the information they need to locate a specified file is a complete path. Volumes can be rearranged, substituted, or subdivided into many volumes without users or applications needing to change settings.

Your application can designate any directory on a volume other than the root as a volume mount point. Instead of making the root directory a volume mount point, your application should create a subdirectory and make that a volume mount point.

When a volume is mounted, volume mount points refer to the drive, not the medium in the drive. Thus, you need not unmount and mount volumes to change removable media.

You can set multiple volume mount points to refer to the same physical drive. For example, you might have a volume mount point for each of several compact discs, all of which share one CD-ROM drive. Each point refers to the same physical CD-ROM drive, and you can access any disc in the drive from any of the volume mount points. The advantage of setting multiple volume mount points is that the different paths make clear the difference between different CDs' applications, for example between a word processor and a game.

To give a brief example of the use of volume mount points, suppose you have a computer with four volumes on it. You have two partitions on a single hard drive, a CD-ROM drive, and a removable media drive. In a conventional system, you might refer to these volumes as C, D, E, and F, respectively.

To use volume mount points, you might build a directory on C: called \mnt:

mkdir c:\mnt

Below that, you might build directories Ddrive, CDROM, and removeable:

mkdir c:\mnt\Ddrive
mkdir c:\mnt\CDROM
mkdir c:\mnt\removeable

Then you might mount each volume at its volume mount point, using a hypothetical command-line utility called Mountvolume:

mountvolume c:\mnt\Ddrive d:
mountvolume c:\mnt\CDROM e:
mountvolume c:\mnt\removeable f:

At this point, you can refer to the root directory of the removeable drive as either F:\ or as C:\mnt\removeable. You can also refer to files on the mounted volume with a concatenated path. Thus, you can refer to the file "D:\Program Files\Windows NT\Accessories\Wordpad.exe" as "C:\Mnt\Ddrive\Program Files\Windows NT\Accessories\Wordpad.exe".

After the volume mount points have been established, they are maintained through computer restarts automatically.

If a volume fails, paths that cross the failed drive break. Thus, it is best to mount all volumes to the boot drive (usually drive C). It is a useful mnemonic for system administrators to use one directory as the volume mount point for all volumes on the system, but nothing in the volume mount point design requires that you use only one directory.

A volume mount point is a directory where a volume can be mounted but not necessarily where a volume currently is mounted.

NTFS volume mount points are implemented by using reparse points and are subject to their restrictions. For more information, see Reparse Points. Volume mount points are supported by Windows 2000 NTFS and higher. It is not necessary to manipulate reparse points in order to use volume mount points; the volume mount point functions handle all the reparse point details for you.

Because volume mount points are directories, you can rename, remove, move, and otherwise manipulate them, just as you can with directories.

Volume mount points are available only in Windows 2000. Only NTFS volumes can hold a volume mount point, although any local drive can be mounted on one.


Unique Volume Names

Two factors can make it hard to reliably mount a specific volume at a specified volume mount point across operating system restarts. One factor is that two different volumes can have the same label, which makes them indistinguishable except by drive letter. The other factor is that drive letters do not necessarily remain the same. If a computer's administrator does not use the Disk Administrator to enforce drive letters, then drive letters can change as drives are removed from or added to the system.

To solve this problem, the system refers to volumes to be mounted with unique volume names. These are strings of this form:

"\\?\Volume{GUID}\"

where GUID is a globally unique identifier (GUID) that identifies the volume. The \\?\ turns off path parsing and is ignored as part of the path, as discussed in Path Lengths. Note the trailing backslash. All volume mount point functions that take a unique volume name as a parameter require the trailing backslash; all volume mount point functions that return a unique volume name provide the trailing backslash. You can use CreateFile to open a volume by referring to its unique volume name, but without a trailing backslash. When using CreateFile, a unique volume name with a backslash refers to the root directory of the volume.

The operating system assigns a unique volume name to a volume when the computer first encounters it, for example during formatting or installation. The volume mount point functions use unique volume names to refer to volumes. To learn the unique volume name of any drive, use the GetVolumeNameForVolumeMountPoint function.


Path Lengths

Path lengths may be a concern when a volume with a deep directory tree is mounted to another volume. This is because paths are concatenated by mounting. The path of a file on a mounted volume thus includes the path of the volume mount point. The globally defined constant MAX_PATH defines the maximum number of characters a path can have. You can avoid this constraint by doing both of the following:

  • Referring to volumes by their unique volume names, which have \\? prepended to the path.
  • Using Unicode so that you use the Unicode (W) versions of file functions, which support the \\? prefix.

The \\?\ turns off path parsing. By using this form, you can work with paths that are nearly 32,000 Unicode characters long. However, each component in the path cannot be more than a file-system-specific value indicated by the function GetVolumeInformation. You must use full paths with this technique. This technique also works with universal naming convention (UNC) names such as "\\OtherComputer\Directory\Filename.ext".

The \\?\ is ignored as part of the path example, and "\\?\C:\myworld\private" is seen as "C:\myworld\private".


Mounting a Volume

Mounting a volume is a two-step process. First, call GetVolumeNameForVolumeMountPoint with the DOS drive letter of the volume you want to mount. Then, use the returned unique volume name and the directory where you want to mount the volume in a call to SetVolumeMountPoint. See Mounting a Volume at a Mount Point.


Enumerating Volumes

To make a complete list of the volumes on a computer, or to manipulate each volume in turn, you can enumerate volumes. Within a volume, you can scan for volume mount points or other objects on the volume.

Three functions allow an application to enumerate volumes on a computer:

  • FindFirstVolume
  • FindNextVolume
  • FindVolumeClose

These three functions operate in a manner very similar to the FindFirstFile, FindNextFile, and FindClose functions.

Begin a search for volumes with FindFirstVolume. If the search is successful, process the results according to the design of your application. Then use FindNextVolume in a loop to locate and process each subsequent volume. When the supply of volumes is exhausted, close the search with FindVolumeClose.

You should not assume any correlation between the order of volumes returned with these functions and the order of volumes returned by other tools. In particular, do not assume any correlation between volume order and drive letters as assigned by the BIOS (if any) or the Disk Administrator.

See Volume Mount Point Examples for an example of how to enumerate the volumes on a computer.


Scanning Volume Mount Points on a Volume

To enumerate all of the volume mount points on a volume, or to manipulate each in turn, scan a volume for volume mount points. Three functions allow an application to enumerate the volume mount points on a specified NTFS volume:

  • FindFirstVolumeMountPoint
  • FindNextVolumeMountPoint
  • FindVolumeMountPointClose

These three functions operate in a manner very similar to the FindFirstFile, FindNextFile, and FindClose functions.

To enumerate volume mount points on a volume, first find out if the volume is a Windows 2000 NTFS volume and thus supports volume mount points. To do so, use the volume name returned by the FindFirstVolume and FindNextVolume functions to call the GetVolumeInformation function. The names returned include a trailing backslash (\) to be compatible with the GetDriveType function and related functions. For more information on the functions used to scan the volumes on a computer, see Enumerating Volumes.

If the volume is an NTFS volume and supports volume mount points, begin a search for the volume's volume mount points with FindFirstVolumeMountPoint. If the search is successful, process the results according to your application's requirements. Then use FindNextVolumeMountPoint in a loop to locate and process each subsequent volume mount point. When the supply of volume mount points is exhausted, close the process with FindVolumeMountPointClose.

Volume mount point searches are confined to the specified volume. To search all of the volume mount points on a computer, use the volume enumerating functions to scan all the volumes, and search each volume in turn. For more information, see Enumerating Volumes.

You should not assume any correlation between the order of volume mount points returned by these functions and the order of volume mount points returned by other tools.

See Volume Mount Point Examples for an example of how to enumerate the mount points on a volume.


Checking Directories for Volume Mount Points

It is useful to determine if a directory is a volume mount point when, for example, you are using a backup utility or search utility that is constrained to one volume. Such a utility can reach information on multiple volumes if you mount all volumes to the one the utility addresses.

To determine if a specified directory is a volume mount point, first call the GetFileAttributes function and inspect the FILE_ATTRIBUTE_REPARSE_POINT flag in the return value to see if the directory has an associated reparse point. If it does, use the FindFirstFile and FindNextFile functions to obtain the reparse tag. To determine if the reparse point is a volume mount point (and not some other form of reparse point), test whether the tag value equals the value IO_REPARSE_TAG_MOUNT_POINT. For more information, see Reparse Points.

To obtain the target volume of a volume mount point, use the function GetVolumeNameForVolumeMountPoint.


Persistent Assignment of Drive Letters

You can assign a drive letter (for example, x:\) to a local volume using SetVolumeMountPoint, provided there is no volume already assigned to that drive letter. If the local volume already has a drive letter then SetVolumeMountPoint will fail. To handle this, first delete the drive letter using DeleteVolumeMountPoint.

Windows 2000 or later: Allows at most one drive letter per volume, so you cannot have C:\ and F:\ pointing to the same volume.

Caution Deleting an existing drive letter and assigning a new one may break existing paths, such as those in desktop shortcuts. It may also break the path to the program making the drive letter changes. With Windows 2000's virtual memory management, this may break the application, leaving the system in an unstable and possibly unusable state. It is the program designer's responsibility to avoid such potential catastrophes.


Volume Mount Point Reference

The volume mount point functions can be divided into three groups: general-purpose functions, functions used to scan for volumes, and functions used to scan a volume for volume mount points.

General-Purpose Volume Mount Point Functions

Function | Description
DeleteVolumeMountPoint | Unmounts a volume from the specified volume mount point.
GetVolumeNameForVolumeMountPoint | Returns the unique volume name for a specified volume mount point or root directory.
GetVolumePathName | Returns the volume mount point at which the specified path is mounted.
SetVolumeMountPoint | Mounts the specified volume at the specified volume mount point.

Volume Mount Point Volume-Scanning Functions

Function | Description
FindFirstVolume | Returns the name of a volume on a computer. FindFirstVolume is used to begin enumerating the volumes of a computer.
FindNextVolume | Continues a volume search started by a call to FindFirstVolume.
FindVolumeClose | Closes a search for volumes.

Volume Mount Point Scanning Functions

Function | Description
FindFirstVolumeMountPoint | Returns the name of a volume mount point on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the volume mount points on a volume.
FindNextVolumeMountPoint | Continues a volume mount point search started by a call to FindFirstVolumeMountPoint.
FindVolumeMountPointClose | Closes a search for volume mount points.


NTFS Change Journal

The NTFS file system maintains a log or change journal that records changes to files. NTFS maintains the change journal in order to recover file system indexing, for example after a computer or volume failure. The ability to recover indexing means the file system can avoid the time-consuming process of reindexing the whole volume in such cases. The change journal software is available only with the Microsoft® Windows® 2000 operating system.

The change journal provides support for any service that tracks changes to a volume. Such services can include indexing packages as well as storage management software.

As files, directories, and other NTFS objects are added, deleted, and modified, NTFS enters records into the change journal in streams, one for each volume on the computer. Each record indicates the type of change and the object changed. The offset from the beginning of the stream for a particular record is called the update sequence number (USN) for the particular record. New records are appended to the end of the stream.

NTFS may delete old records in order to conserve space. If needed records have been deleted, the indexing service recovers by reindexing the volume, as it does when no change journal exists.

The change journal logs only the fact of a change to a file and the reason for the change (for example, write operations, truncation, lengthening, deletion, and so on). It does not record enough information to allow reversing the change.

In addition, multiple changes to the same file may result in only one reason flag being added to the current record. If the same kind of change occurs more than once, NTFS does not write a new record for the changes after the first. For example, several write operations with no intervening close and reopen operations result in only one change record with the reason flag USN_REASON_DATA_OVERWRITE set.

To illustrate how the change journal works, suppose a user accesses a file in the following fashion:

  1. Writes to the file.
  2. Sets the time stamp for the file.
  3. Writes to the file.
  4. Truncates the file.
  5. Writes to the file.
  6. Closes the file.

In this case, NTFS takes the following actions in the change journal (where | indicates a bitwise OR operation).

Event | NTFS action
Initial write operation | NTFS writes a new USN record with the USN_REASON_DATA_OVERWRITE reason flag set. For more information on possible reason flags, see the USN_RECORD structure topic.
Setting of file time stamp | NTFS writes a new USN record with the flag setting USN_REASON_DATA_OVERWRITE | USN_REASON_BASIC_INFO_CHANGE.
Second write operation | NTFS does not write a new USN record. Because USN_REASON_DATA_OVERWRITE is already set for the existing record, no changes are made to the record.
File truncation | NTFS writes a new USN record with the flag setting USN_REASON_DATA_OVERWRITE | USN_REASON_BASIC_INFO_CHANGE | USN_REASON_DATA_TRUNCATION.
Third write operation | NTFS does not write a new USN record. Because USN_REASON_DATA_OVERWRITE is already set for the existing record, no changes are made to the record.
Close operation | If the user making changes is the only user of the file, NTFS writes a new USN record with the following flag setting: USN_REASON_DATA_OVERWRITE | USN_REASON_BASIC_INFO_CHANGE | USN_REASON_DATA_TRUNCATION | USN_REASON_CLOSE.

The change journal accumulates a series of records between the first opening and last closing of a file. Each record has a new reason flag set, indicating that a new kind of change has occurred. The sequence of records gives a partial history of the file. The final record, created when the file is closed, adds the USN_REASON_CLOSE flag. This record represents a summary of changes to the file, but unlike the prior records, gives no indication of the order of the changes.

The next user to access and change the file generates a new USN record with a single reason flag.


Using the Change Journal Identifier

NTFS associates an unsigned 64-bit identifier with each change journal. The journal is stamped with this identifier when it is created. The file system restamps the journal with a new identifier where the existing USN records either are or may be unusable.

For example, NTFS restamps a change journal with a new identifier when a volume is moved from Windows 2000 to Microsoft® Windows NT® version 4.0 and then back to Windows 2000. Such a move can happen in a dual-boot environment or when working with removable media.

To obtain the identifier of the current change journal on a specified volume, use the FSCTL_QUERY_USN_JOURNAL operation for the DeviceIoControl function. To perform this and all other change journal operations, you must have system administrator privileges. That is, you must be a member of the Administrators group.

When an administrator deletes and recreates the change journal, for example when the current USN value approaches the maximum possible USN value, the USN values begin again from zero. When NTFS stamps a journal with a new identifier rather than recreating the journal, it does not reset the USN to zero but continues from the current USN. In either case, all existing USNs are less than any future USNs.

When you need information on a specific set of records, use the DeviceIoControl operation FSCTL_QUERY_USN_JOURNAL to obtain the change journal identifier. Then use the FSCTL_READ_USN_JOURNAL operation to read the journal records of interest. NTFS only returns records that are valid for the journal specified by the identifier.

Your application needs both the records' USNs and the identifier to read the journal. This requirement provides an integrity check for cases where your application should ignore the existing records in the file and where records were written in previous instances of the journal for the same volume.

To obtain the records in which you are interested, you must start at the oldest record (that is, with the lowest USN) and scan forward until you locate the first record of interest.

Note In order for a Windows NT 4.0 system to read an NTFS file system in Windows 2000, either you should upgrade the Windows NT 4.0 system to Windows NT 4.0 Service Pack 4 or higher, or install Windows 2000 on the same computer. Installation of Windows 2000 beta 2 or higher upgrades Windows NT 4.0 to read and write Windows 2000 volumes and upgrades all volumes to Windows 2000 NTFS.

The Windows NT 4.0 drivers for NTFS volumes in Windows 2000 do not maintain the change journal, and Windows NT 4.0 does not allow access to the change journal.


Creating, Modifying, and Deleting a Change Journal

Administrators can use the Windows 2000 user interface to create, delete, and recreate change journals at will. An administrator should delete a journal when the current USN value approaches the maximum possible USN value, as indicated by the MaxUsn member of the USN_JOURNAL_DATA structure. An administrator might also delete and recreate a change journal to reclaim disk space. To perform this and all other nonprogrammatic change journal operations, you must have system administrator privileges. That is, you must be a member of the Administrators group.

To create or modify a change journal on a specified volume programmatically, use the FSCTL_CREATE_USN_JOURNAL operation with the function DeviceIoControl.

When you create a new change journal or modify an existing one, NTFS sets information for that change journal from information in the CREATE_USN_JOURNAL_DATA structure, which FSCTL_CREATE_USN_JOURNAL takes as input. CREATE_USN_JOURNAL_DATA has the members MaximumSize and AllocationDelta.

MaximumSize is the target maximum size for the change journal in bytes. The change journal can grow larger than this value, but at NTFS checkpoints NTFS examines the journal and trims it when its size exceeds the value of MaximumSize plus the value of AllocationDelta. (At NTFS checkpoints, the operating system writes records to the NTFS log file that allow NTFS to determine what processing is required to recover from a failure.)

AllocationDelta is the number of bytes added to the end and removed from the beginning of the change journal each time memory is allocated or deallocated. In other words, allocation and deallocation take place in units of this size. An integer multiple of a cluster size is a reasonable value for this member.

If an administrator modifies an existing change journal to have a larger MaximumSize value, for example if a volume is being reindexed too often, the change journal simply receives new entries until it exceeds the new maximum size.

To delete a change journal, use the FSCTL_DELETE_USN_JOURNAL operation with DeviceIoControl. When you use this operation, the operation walks through all of the files on the volume and resets the USN for each file to zero. The operation then deletes the existing change journal. This operation persists across system restarts until it completes. Any attempt to read, create, or modify the change journal during this process fails with the error code ERROR_JOURNAL_DELETE_IN_PROGRESS.

You can also use the FSCTL_DELETE_USN_JOURNAL operation to determine if a deletion started by some other process is in progress. For example, your application, when it is started, can determine if a deletion is in progress. Because journal deletions persist across system restarts, services and applications started at system restart should check for an ongoing deletion.

Change journals are not necessarily created at startup. To create a change journal, an administrator may do so explicitly or start another service that requires a change journal.


Obtaining a Volume Handle for Change Journal Operations

To obtain a handle to a volume for use with change journal operations, pass in the lpFileName parameter of the CreateFile function a value of the following form:

\\.\X:

where X is the letter identifying the drive on which the volume appears. The volume must be an NTFS volume on Windows 2000.


Walking a Buffer of Change Journal Records

The two operations for the DeviceIoControl function that return change journal records, FSCTL_READ_USN_JOURNAL and FSCTL_ENUM_USN_DATA, return almost the same data. Both return zero or more change journal records, each in a USN_RECORD structure. Use FSCTL_ENUM_USN_DATA when you want a listing (enumeration) of all change journal records between two USNs. Use FSCTL_READ_USN_JOURNAL when you want to be more selective, such as selecting specific reasons for changes or returning when a file is closed.

USN_RECORD contains the name of the file to which the record in question applies. The file name varies in length, so USN_RECORD is a variable-length structure. Its first member, RecordLength, is the length of the structure (including the file name) in bytes. Returned USN_RECORD structures are aligned on 64-bit boundaries.

Both of these operations return only the subset of change journal records between the boundaries specified. These operations also return the next record number to be retrieved, so that you can continue reading records from the end boundary forward.

To walk the buffer of change journal records returned by either operation from the first entry onward, you must round up the length of the buffer to match the alignment of the USN_RECORD structures, as shown in the following example. Use a function such as the following to calculate the location of the next USN_RECORD structure in memory. This function accepts a pointer to a USN_RECORD structure. It does not test to see if a valid record is present at that address.

// Note that the following is an inline function.

__inline PUSN_RECORD
nextentry(const PUSN_RECORD input)
{
  register DWORD output;

  // Get the base address of the current record.
  (PUSN_RECORD) output = input;

  // Add the size of the record (structure + file name after the end
  // of the structure).
  output += input->RecordLength;

  // Round up the record size to match the 64-bit alignment, if the
  // size is not already a multiple of 8. Perform a bitwise AND
  // operation here instead of division because it is much faster than
  // division. However, the bitwise AND operation only works because
  // the divisor 8 is a power of 2.

  if(output & 8-1)
    {
      // Round down to nearest multiple of 8.
      output &= -8;
      // Then add 8.
      output += 8;
    }

  return((PUSN_RECORD) output);
}

To simplify matters, when you read records from a change journal declare your input buffer on a 64-bit boundary. That way, the first record always occurs at the boundary equal to the value of the DeviceIoControl lpOutBuffer parameter plus 8.

The size in bytes of any record specified by a USN_RECORD structure is at most ((MaximumComponentLength - 1) * Width) + Size where MaximumComponentLength is the maximum length, in characters, of the record's file name, Width is the size of a wide character, and Size is the size of the structure. To obtain this maximum length, call the GetVolumeInformation function and examine the value pointed to by the lpMaximumComponentLength parameter. You subtract one from MaximumComponentLength to account for the fact that the definition of USN_RECORD includes one character of the file name.

Thus, in C the largest possible record size is:

(MaximumComponentLength * sizeof(WCHAR) + sizeof(USN_RECORD) - sizeof(WCHAR))

When working with the FileName member of USN_RECORD, do not count on the change journal's file name containing a trailing '\0' delimiter. To determine the length of the file name, use the FileNameLength member.


Change Journal Operations

The following DeviceIoControl function operations work with the NTFS change journal.

FSCTL_CREATE_USN_JOURNAL
FSCTL_DELETE_USN_JOURNAL
FSCTL_ENUM_USN_DATA
FSCTL_MARK_HANDLE
FSCTL_QUERY_USN_JOURNAL
FSCTL_READ_USN_JOURNAL


Change Journal Structures

The following structures hold information relating to the NTFS change journal.

CREATE_USN_JOURNAL_DATA
DELETE_USN_JOURNAL_DATA
MARK_HANDLE_INFO
MFT_ENUM_DATA
READ_USN_JOURNAL_DATA
USN_JOURNAL_DATA
USN_RECORD


Defragmentation

A file is stored on a disk drive (and other media) in one or more clusters. Clusters are the atomic unit of data allocation, made up of one or more sectors. Sectors, in turn, are physical storage units.

As a file is written to the disk, the file may not be written in contiguous clusters. Noncontiguous clusters slow down the process of reading and writing the file. The farther apart on the disk the noncontiguous clusters are, the worse the problem because of the time it takes to move the hard drive's read/write head. A file with noncontiguous clusters is said to be fragmented. To optimize files for fast access, a volume may be defragmented.

Defragmentation is the process of moving portions of files around on the disk in order to defragment files; that is, the process of moving a file's clusters on the disk to make them contiguous.

In a simple single-tasking operating system, defragmentation is straightforward: the defragmentation software is the sole task, and there are no other processes to read from or write to the disk. However, in a multitasking operating system, some processes may be reading from and writing to the hard drive while another process is trying to defragment that hard drive. The trick is to avoid writes to the file being defragmented without stopping the writing process for very long. Solving this problem is not trivial, but it is possible.

Some file systems are publicly documented, such as the FAT16 and FAT32 file systems used in the Microsoft® MS-DOS® and Windows® 98 operating systems. This allows programmers to manipulate on-disk data structures (such as file allocation tables, or FATs) directly. However, NTFS, the file system that the Windows NT® operating system uses, is deliberately opaque. To allow defragmentation of NTFS without requiring detailed knowledge of the disk structure of NTFS, a set of three DeviceIoControl operations is provided. The three operations allow applications to locate empty clusters, determine the disk location of file clusters, and move clusters on the disk. The DeviceIoControl operations transparently handle the problem of inhibiting and allowing other processes to read from and write to files during moves.

These same DeviceIoControl operations also work with FAT volumes.

These operations can be performed without inhibiting other processes from running. However, the other processes will have slower response times while a disk drive is being defragmented.

Clusters may be referred to from two different perspectives: within the file and on the volume. Any cluster in a file has a virtual cluster number (VCN), which is its relative offset from the beginning of the file. For example, a seek to twice the size of a cluster, followed by a read, will return data beginning at the third VCN. A logical cluster number (LCN) describes the offset of a cluster from some arbitrary point within the volume. LCNs should be treated only as ordinal, or relative, numbers. There is no guaranteed mapping of logical clusters to physical hard drive sectors.

An extent is a run of contiguous clusters. For example, suppose a file consisting of thirty clusters is recorded in two extents. The first extent might consist of five contiguous clusters, the other of the remaining 25 clusters.

There is no guarantee of any relationship on the disk of any extent to any other extent. For example, the first extent may be at a higher LCN than a subsequent extent.

To defragment a file:

  1. Use the DeviceIoControl FSCTL_GET_VOLUME_BITMAP operation to find a place on the volume large enough to accept the entire file. If necessary, move other files to make a place that's large enough. Ideally, there will be enough unallocated clusters after the first extent of the file that you can simply move subsequent extents into the space after the first extent.
  2. Use the DeviceIoControl FSCTL_GET_RETRIEVAL_POINTERS operation to get a map of the current layout of the file on the disk.
  3. Walk the RETRIEVAL_POINTERS_BUFFER structure returned by FSCTL_GET_RETRIEVAL_POINTERS. Use the DeviceIoControl FSCTL_MOVE_FILE operation to move each cluster as you walk the structure. You may need to renew either the bitmap or the retrieval structure, or both, from time to time as other processes write to the disk.

Two of the operations used for defragmentation require handles to volumes. Only administrators can open volumes to handles, so only administrators can run defragmentation software. Your program should check the privileges of the user executing it, and gracefully refuse to run for nonadministrators.

The DeviceIoControl FSCTL_MOVE_FILE operation only operates on NTFS volumes with a cluster size less than 4K. NTFS format defaults to cluster sizes of less than 4K, so volumes with cluster sizes larger than 4K are rare.

Defragmentation DeviceIoControl Operations

FSCTL_GET_VOLUME_BITMAP

FSCTL_GET_RETRIEVAL_POINTERS

FSCTL_MOVE_FILE

The following is a table of defragmentation structures and the Associated DeviceIoControl operation.

Defragmentation structures | Operation
MOVE_FILE_DATA | FSCTL_MOVE_FILE
RETRIEVAL_POINTERS_BUFFER | FSCTL_GET_RETRIEVAL_POINTERS
STARTING_LCN_INPUT_BUFFER | FSCTL_GET_VOLUME_BITMAP
STARTING_VCN_INPUT_BUFFER | FSCTL_GET_RETRIEVAL_POINTERS
VOLUME_BITMAP_BUFFER | FSCTL_GET_VOLUME_BITMAP


FAT File System

The File Allocation Table (FAT) file system organizes data on fixed disks and floppy disks. The distinguishing feature of the FAT file system is its file name convention. The file name convention consists of a file name (up to eight characters), a separating period (.), and a file name extension (up to three characters).

The main advantage of FAT volumes is that they are accessible by MS-DOS, Microsoft® Windows®, and OS/2 systems. FAT is also the only file system currently supported on floppy disks and other removable media.

Valid FAT file names have the following form:

[[drive:]][[directory\]]filename[[.extension]]

The drive parameter must name an existing drive and can be any letter from A through Z. The drive letter must be followed by a colon (:).

The directory parameter specifies the directory that contains the file's directory entry. This value must be followed by a backslash (\) to separate it from the file name. If the specified directory is not in the current directory, directory must include the names of all directories in the file's path, separated by backslashes. The root directory is specified by using a backslash at the beginning of the name. For example, if the directory ABCD is in the directory SAMPLE and SAMPLE is in the root directory, the correct directory specification is \SAMPLE\ABCD. A directory name consists of any combination of up to eight letters, digits, or the following special characters:

$ % ' – _ @ { } ~ ` ! # ( )

A directory name can also have an extension that is any combination of up to three letters, digits, or special characters, preceded by a period (.).

The filename and extension parameters specify the file. Filename can be any combination of up to eight letters, digits, or the special characters previously listed; extension can be any combination of up to three letters, digits, or special characters, all preceded by a period. Filename can also include embedded (preceded and followed by one or more letters, digits, or special characters just noted) spaces. For example, the string "disk 1" is a valid value for filename.

FAT volumes do not distinguish between uppercase and lowercase letters.


Protected-Mode FAT File System

The protected-mode FAT file system organizes data on fixed and floppy disks. Protected-mode FAT is compatible with the FAT file system, using file allocation tables and directory entries to store information about the contents of a disk. Protected-mode FAT also supports long file names, storing these names and other information such as the date and time the file was last accessed in the FAT structures.

Protected-mode FAT allows file names of up to 255 characters, including the terminating null character. This is similar to NTFS, which allows file names of up to 256 characters.

Protected-mode FAT allows paths of up to 260 characters, including the terminating null character.


Using File System Features

The examples in this section demonstrate how to use the file system features.

  • Volume Mount Point Examples


Volume Mount Point Examples

The following samples illustrate the volume mount point functions.

  • Editing Drive Letter Assignments
  • Mounting a Volume at a Mount Point
  • Enumerating Mount Points
  • Enumerating Unique Volume Names
  • Unmounting a Volume at a Mount Point


Editing Drive Letter Assignments

The following sample demonstrates how to add or remove persistent drive letter assignments in Windows 2000. These drive letter assignments persist through machine reboots.

This sample uses the following functions: DefineDosDevice, DeleteVolumeMountPoint, GetVolumeNameForVolumeMountPoint, and SetVolumeMountPoint.

/*
DLEDIT  -- Drive Letter Assignment Editor

Platforms:
   This program requires Windows 2000.

Command-line syntax:
   DLEDIT <drive letter> <NT device name>      -- Adds a drive letter
   DLEDIT -r <drive letter>                    -- Removes a drive letter

Command-line examples:

   If E: refers to the CD-ROM drive, use the following commands to
   make F: point to the CD-ROM drive instead.

   DLEDIT -r E:\
   DLEDIT F:\ \Device\CdRom0

*****************************************************************
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

   This program will change drive letter assignments, and the
   changes persist through reboots. Do not remove drive letters
   of your hard disks if you do not have this program on floppy
   disk or you might not be able to access your hard disks again!
*****************************************************************
*/

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <stdio.h>

#if defined (DEBUG)
   static void DebugPrint (LPCSTR pszMsg, DWORD dwErr);
   #define DEBUG_PRINT(pszMsg, dwErr) DebugPrint(pszMsg, dwErr)
#else
   #define DEBUG_PRINT(pszMsg, dwErr) NULL
#endif

#pragma warning (disable : 4800)

void PrintHelp (LPCSTR pszAppName);

/*--------------------------------------------------------------------
The main function is the main routine. It parses the command-line
arguments and either removes or adds a drive letter.

Parameters
   argc
      Count of the command-line arguments
   argv
      Array of pointers to the individual command-line arguments

--------------------------------------------------------------------*/
void main (int argc, char **argv)
{
   char * pszDriveLetter,
        * pszNTDevice,
        * pszOptions;

   char szUniqueVolumeName[MAX_PATH];
   char szDriveLetterAndSlash[4];
   char szDriveLetter[3];

   bool  fRemoveDriveLetter;
   bool  fResult;

   if (argc != 3)
   {
      PrintHelp(argv[0]);
      return;
   }

   // Use the command line to see if user wants to add or remove the
   // drive letter. Do this by looking for the -r option.

   fRemoveDriveLetter = !lstrcmpi (argv[1], "-r");

   if (fRemoveDriveLetter)
   {
      // User wants to remove the drive letter. Command line should
      // be: dl -r <drive letter>

      pszOptions       = argv[1];
      pszDriveLetter   = argv[2];
      pszNTDevice      = NULL;
   }
   else
   {
      // User wants to add a drive letter. Command line should be:
      // dl <drive letter> <NT device name>

      pszOptions       = NULL;
      pszDriveLetter   = argv[1];
      pszNTDevice      = argv[2];
   }

   // GetVolumeNameForVolumeMountPoint, SetVolumeMountPoint, and
   // DeleteVolumeMountPoint require drive letters to have a trailing
   // backslash. However, DefineDosDevice requires that the trailing
   // backslash be absent. So, we'll use:
   //
   //    szDriveLetterAndSlash     for the mount point APIs
   //    szDriveLetter             for DefineDosDevice
   //
   // This way, we can accept command lines that use a: or a:\
   // for drive letters without writing back to the original command-
   // line argument.

   szDriveLetter[0] = pszDriveLetter[0];
   szDriveLetter[1] = ':';
   szDriveLetter[2] = '\0';

   szDriveLetterAndSlash[0] = pszDriveLetter[0];
   szDriveLetterAndSlash[1] = ':';
   szDriveLetterAndSlash[2] = '\\';
   szDriveLetterAndSlash[3] = '\0';

   // Now add or remove the drive letter.

   if (fRemoveDriveLetter)
   {
      fResult = DeleteVolumeMountPoint (szDriveLetterAndSlash);

      if (!fResult)
         printf("error %lu: couldn't remove %s\n",
                GetLastError(), szDriveLetterAndSlash);
   }
   else
   {
      // To add a drive letter that persists through reboots, use
      // SetVolumeMountPoint. This requires the unique volume name of
      // the device to which the new drive letter will refer. To get
      // the unique volume name, use GetVolumeNameForVolumeMountPoint;
      // it requires the drive letter to already exist. So, we first
      // define the drive letter as a symbolic link to the device
      // name. After we have the unique volume name the new drive
      // letter will point to, we must delete the symbolic link
      // because the mount manager allows only one reference to a
      // device at a time (the new one to be added).

      fResult = DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter,
                                 pszNTDevice);

      if (fResult)
      {
          // If GetVolumeNameForVolumeMountPoint fails, then
          // SetVolumeMountPoint will also fail. However, we must call
          // DefineDosDevice to remove the temporary symbolic link.
          // Therefore, set szUniqueVolume to a known empty string.

         if (!GetVolumeNameForVolumeMountPoint (szDriveLetterAndSlash,
                  szUniqueVolumeName,
                  MAX_PATH))
         {
            DEBUG_PRINT("GetVolumeNameForVolumeMountPoint failed",
                        GetLastError());
            szUniqueVolumeName[0] = '\0';
         }

         fResult = DefineDosDevice (
                      DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|
                      DDD_EXACT_MATCH_ON_REMOVE, szDriveLetter,
                      pszNTDevice);

         if (!fResult)
            DEBUG_PRINT("DefineDosDevice failed", GetLastError());

         fResult = SetVolumeMountPoint (szDriveLetterAndSlash,
                        szUniqueVolumeName);

         if (!fResult)
            printf ("error %lu: could not add %s\n", GetLastError(),
                    szDriveLetterAndSlash);
      }
   }
}

/*-------------------------------------------------------------------
The PrintHelp function prints the command-line usage help.

Parameters
   pszAppName
      The name of the executable. Used in displaying the help.

-------------------------------------------------------------------*/
void PrintHelp (LPCSTR pszAppName)
{
   printf("Adds/removes a drive letter assignment for a device.\n\n");
   printf("Usage: %s <Drive> <Device name>   add a drive letter\n", pszAppName);
   printf("       %s -r <Drive>              remove a drive letter\n\n", pszAppName);
   printf("Example: %s e:\\ \\Device\\CdRom0\n", pszAppName);
   printf("         %s -r e:\\\n", pszAppName);
}

#if defined (DEBUG)
/*--------------------------------------------------------------------
The DebugPrint function prints a string to STDOUT.

Parameters
   pszMsg
      The string to be printed to STDOUT.
   dwErr
      The error code; usually obtained from GetLastError. If dwErr is
      zero, no error code is added to the error string. If dwErr is
      nonzero, the error code will be printed in the error string.
--------------------------------------------------------------------*/
void DebugPrint (LPCSTR pszMsg, DWORD dwErr)
{
   if (dwErr)
      printf("%s: %lu\n", pszMsg, dwErr);
   else
      printf("%s\n", pszMsg);
}
#endif

When building this sample program, use the following makefile.

APPVER = 5.0
TARGETOS = WINNT

!include <win32.mak>

PROJ = DLEDIT

all: $(PROJ).exe

PROJ_OBJS = dledit.obj

.cpp.obj:
    $(cc) $(cdebug) $(cflags) $(cvars) $<

$(PROJ).exe: $(PROJ_OBJS)
    $(link) $(ldebug) $(conlflags)\
    $(PROJ_OBJS) \
    -out:$(PROJ).exe \
    $(conlibs)

clean:
    del *.bak
    del *.opt
    del *.pdb
    del *.obj

cleaner: clean
    del *.exe


Mounting a Volume at a Mount Point

The following sample demonstrates how to mount a file system.

This sample uses the following functions: GetVolumeNameForVolumeMountPoint and SetVolumeMountPoint.

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <stdio.h>

#define BUFSIZE 1024    // ample space for our string buffer

void
Syntax (char *argv)
{
   printf( "%s, mount a volume at a mount point.\n", argv );
   printf( "For example, \"mount c:\\mnt\\fdrive\\ f:\\\"\n" );
}

int
main( int argc, char *argv[] )
{
   BOOL bFlag;
   char Buf[BUFSIZE];            // temporary buffer for volume name

   if( argc != 3 )
   {
      Syntax( argv[0] );
      return( -1 );
   }

  // We should do some error checking on the inputs. Make sure
  // there are colons and backslashes in the right places, etc.

   bFlag = GetVolumeNameForVolumeMountPoint(
              argv[2], // input volume mount point or directory
                  Buf, // output volume name buffer
               BUFSIZE // size of volume name buffer
           );

   if (bFlag != TRUE)
   {
      printf( "Retrieving volume name for %s failed.\n", argv[2] );
      return (-2);
   }
   printf( "Volume name of %s is %s\n", argv[2], Buf );

   bFlag = SetVolumeMountPoint(
              argv[1], // mount point
                   Buf // volume to be mounted
           );

   if (!bFlag)
     printf ("Attempt to mount %s at %s failed.\n", argv[2], argv[1]);

   return (bFlag);
}


Enumerating Mount Points

The following sample demonstrates how to enumerate volumes and mount points on a computer.

This sample uses the following functions: DeleteVolumeMountPoint, FindFirstVolume, FindFirstVolumeMountPoint, FindNextVolume, FindNextVolumeMountPoint, FindVolumeClose, FindVolumeMountPointClose, GetVolumeInformation, and GetVolumeNameForVolumeMountPoint.

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <stdio.h>

#define BUFSIZE 1024            // ample space for our string buffer
#define FILESYSNAMEBUFSIZE 1024 // probably more than we need

// Process each mount point found here. This makes maintenance easier
// than doing it in line. The result indicates whether there is
// another mount point to be scanned.

// This routine prints out the path to a mount point and its target.

BOOL ProcessVolumeMountPoint (HANDLE hPt,
                              char *PtBuf, DWORD dwPtBufSize,
                              char *Buf, DWORD dwBufSize)
{
   BOOL bFlag;                   // Boolean result
   char Path[BUFSIZE];           // construct a complete path here
   HANDLE hFf, hFile;            // file search, file handles
   WIN32_FIND_DATA fd;           // find data for a file search
   DWORD BytesReturned;          // from DeviceIoControl call
   char Target[BUFSIZE];         // target of mount at mount point

   printf ("\tVolume mount point found is \"%s\"\n", PtBuf);

   // Detect the volume mounted there. Unfortunately, there is no
   // simple way to map a unique volume name to a DOS drive letter.
   // One way to do that is to build an associative array, which we
   // will "leave as an exercise for the student."

   // Build a unique path to the mount point

   strcpy (Path, Buf);
   strcat (Path, PtBuf);

   bFlag = GetVolumeNameForVolumeMountPoint(
                Path, // input volume mount point or directory
              Target, // output volume name buffer
              BUFSIZE // size of volume name buffer
           );

   if (!bFlag)
      printf ("\tAttempt to get Volume Name for %s failed.\n", Path);
   else
      printf ("\tTarget of the volume mount point is %s.\n", Target);

   // Now, either get the next mount point and return it, or return a
   // value indicating there are no more mount points.

   bFlag = FindNextVolumeMountPoint(
                     hPt, // handle to scan
                   PtBuf, // pointer to output string
              dwPtBufSize // size of output buffer
           );

  return (bFlag);
}

// Process each volume. This makes maintenance easier than doing it
// in line. The Boolean result indicates whether there is another
// volume to be scanned.

BOOL ProcessVolume (HANDLE hVol, char *Buf, int iBufSize)
{
   BOOL bFlag;                  // generic results flag for return
   HANDLE hPt;                  // handle for mount point scan
   char PtBuf[BUFSIZE];         // string buffer for mount points
   DWORD dwSysFlags;            // flags that describe the file system
   char FileSysNameBuf[FILESYSNAMEBUFSIZE];

   printf ("Volume found is \"%s\".\n", Buf);

   // Is this volume NTFS?
  GetVolumeInformation( Buf, NULL, 0, NULL, NULL,
                        &dwSysFlags, FileSysNameBuf,
                        FILESYSNAMEBUFSIZE);

   // Detect support for reparse points, and therefore for volume
   // mount points, which are implemented using reparse points.

   if (! (dwSysFlags & FILE_SUPPORTS_REPARSE_POINTS))
   {
      printf ("\tThis file system does not support Volume Mount Points.\n");
   }
   else
   {
      // Start processing mount points on this volume.

      hPt = FindFirstVolumeMountPoint(
                  Buf, // root path of volume to be scanned
                PtBuf, // pointer to output string
               BUFSIZE // size of output buffer
            );

      // Shall we error out?

      if (hPt == INVALID_HANDLE_VALUE)
      {
         printf ("\tNo volume mount points found!\n");
      }
      else
      {
         // Process the volume mount point.
         bFlag = ProcessVolumeMountPoint (hPt, PtBuf, BUFSIZE, Buf, BUFSIZE);

         // Do while we have volume mount points to process.
         while (bFlag)
            bFlag = ProcessVolumeMountPoint (hPt, PtBuf, BUFSIZE, Buf, BUFSIZE);

         FindVolumeMountPointClose(hPt);
       }
   }

  // Stop processing mount points on this volume.

   bFlag = FindNextVolume(
                hVol, // handle to scan being conducted
                 Buf, // pointer to output
             iBufSize // size of output buffer
           );

   return (bFlag);
}

int
main(int argc, char *argv[])
{
   char buf[BUFSIZE];            // buffer for unique volume identifiers
   HANDLE hVol;                  // handle for the volume scan
   BOOL bFlag;                   // generic results flag

   // Open a scan for volumes.
   hVol = FindFirstVolume (buf, BUFSIZE );

   // Shall we error out?
   if (hVol == INVALID_HANDLE_VALUE)
   {
      printf ("No volumes found!\n");
      return (-1);
   }

   // We have a volume; process it.
   bFlag = ProcessVolume (hVol, buf, BUFSIZE);

   // Do while we have volumes to process.
   while (bFlag)
   {
      bFlag = ProcessVolume (hVol, buf, BUFSIZE);
   }

   // Close out our volume scan.
   bFlag = FindVolumeClose(
              hVol  // handle to be closed
           );

   return (bFlag);
}


Enumerating Unique Volume Names

The following sample demonstrates how to obtain the unique volume name for a specified volume name; for example, "c:\".

This sample uses the GetVolumeNameForVolumeMountPoint function.

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <stdio.h>

#define BUFSIZE 1024   // ample space for our string buffer

int
main(int argc, char *argv[])
{
   BOOL bFlag;
   char Buf[BUFSIZE];          // temporary buffer for volume name
   char Drive[] = "c:\\";      // template drive specifier
   int i;                      // generic loop counter

   // Walk through legal drive letters, skipping floppies.
   for (i = 'c'; i < 'z';  i++ )
   {
      // Stamp the drive for the appropriate letter.
      Drive[0] = (char)i;

      bFlag = GetVolumeNameForVolumeMountPoint(
                 Drive, // input volume mount point or directory
                   Buf, // output volume name buffer
                BUFSIZE // size of volume name buffer
              );

      if (bFlag)
      {
         printf ("The ID of drive %s is \"%s\"\n", Drive, Buf);
      }
   }
}


Unmounting a Volume at a Mount Point

The following sample demonstrates how to unmount a volume mounted at a volume mount point using the DeleteVolumeMountPoint function.

#define _WIN32_WINNT 0x0500

#include <windows.h>
#include <stdio.h>

void
Syntax (char *argv)
{
   printf("%s unmounts a volume from the volume mount point.\n", argv);
   printf ("E.g. \"%s c:\\mnt\\fdrive\\\"\n", argv);
}

int
main(int argc, char *argv[])
{
   BOOL bFlag;

   if (argc != 2)
   {
      Syntax (argv[0]);
      return (-1);
   }

// We should do some error checking on the path argument, such as
// ensuring that there is a trailing backslash.

   bFlag = DeleteVolumeMountPoint(
              argv[1] // Path of the volume mount point
           );

   printf ("%s %s in unmounting the volume at %s.\n",
           argv[0], bFlag ? "succeeded" : "failed", argv[1]);

   return (bFlag);
}


File System Reference

The following functions, interfaces, and structures are used with file systems:

  • File System Functions
  • File System Control Codes
  • File System Interfaces
  • File System Structures
  • File System Macros


File System Functions

The following functions are used with file systems.

Function | Description
CreateHardLink | Establishes an NTFS hard link between an existing file and a new file.
GetCompressedFileSize | Retrieves the actual number of bytes of disk storage used to store a specified file.
GetDiskFreeSpace | Retrieves information about the specified disk, including the amount of free space on the disk.
GetDiskFreeSpaceEx | Retrieves information about the specified disk, including the amount of free space on the disk.
GetFileSize | Retrieves the size of a specified file.
GetFileSizeEx | Retrieves the size of a specified file.
GetLogicalDrives | Returns a bitmask representing the currently available disk drives.
GetLogicalDriveStrings | Fills a buffer with strings that specify valid drives in the system.
GetVolumeInformation | Retrieves information about a file system and volume.
SetVolumeLabel | Sets the label of a file system volume.

The following functions are used with the encrypted file system.

Function | Description
AddUsersToEncryptedFile | Adds user keys to a specified encrypted file.
DecryptFile | Decrypts an encrypted file or directory.
EncryptFile | Encrypts a file or directory.
EncryptionDisable | Disables or enables encryption of the indicated directory and the files in it.
FileEncryptionStatus | Retrieves the encryption status of the specified file.
FreeEncryptionCertificateHashList | Frees a certificate hash list.
QueryRecoveryAgentsOnEncryptedFile | Retrieves a list of recovery agents for the specified file.
QueryUsersOnEncryptedFile | Retrieves a list of users for the specified file.
RemoveUsersFromEncryptedFile | Removes specified certificate hashes from a specified file.
SetUserFileEncryptionKey | Sets the user's current key to the specified certificate.

The following functions are used with volume mount points.

Function | Description
DeleteVolumeMountPoint | Unmounts the volume from the specified volume mount point.
FindFirstVolume | Returns the name of a volume on a computer.
FindFirstVolumeMountPoint | Returns the name of a volume mount point on the specified volume.
FindNextVolume | Continues a volume search started by a call to FindFirstVolume.
FindNextVolumeMountPoint | Continues a volume mount point search started by a call to FindFirstVolumeMountPoint.
FindVolumeClose | Closes the specified volume search handle.
FindVolumeMountPointClose | Closes the specified mount-point search handle.
GetVolumeNameForVolumeMountPoint | Takes a volume mount point or root directory and returns the corresponding unique volume name.
GetVolumePathName | Retrieves the volume mount point at which the specified path is mounted.
GetVolumePathNamesForVolumeName | Retrieves a list of path names for the specified volume name.
SetVolumeMountPoint | Mounts the specified volume at the specified volume mount point.


AddUsersToEncryptedFile

The AddUsersToEncryptedFile function adds user keys to a specified encrypted file.

DWORD AddUsersToEncryptedFile(
  LPCWSTR lpFileName,                  // file name
  PENCRYPTION_CERTIFICATE_LIST pUsers  // user keys
);

Parameters

lpFileName
[in] Pointer to a null-terminated Unicode string that specifies the name of the encrypted file.
pUsers
[in] Pointer to a ENCRYPTION_CERTIFICATE_LIST structure that contains the list of new user keys to be added to the file.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error code. For a complete list of error codes, see Error Codes or the Platform SDK header file WinError.h.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE_LIST


CreateHardLink

The CreateHardLink function establishes an NTFS hard link between an existing file and a new file. An NTFS hard link is similar to a POSIX hard link.

BOOL CreateHardLink(
  LPCTSTR lpFileName,                         // link name name
  LPCTSTR lpExistingFileName,                 // target file name
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

Parameters

lpFileName
[in] Pointer to the name of the new directory entry to be created.
lpExistingFileName
[in] Pointer to the name of the existing file to which the new link will point.
lpSecurityAttributes
Values passed in this parameter will not be processed. Specify NULL as the value of this parameter.

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

Any directory entry for a file, whether created with CreateFile or CreateHardLink, is a hard link to the associated file. Additional hard links, created with the CreateHardLink function, allow you to have multiple directory entries for a file, that is, multiple hard links to the same file. These may be different names in the same directory, or they may be the same (or different) names in different directories. However, all hard links to a file must be on the same volume.

Because hard links are just directory entries for a file, whenever an application modifies a file through any hard link, all applications using any other hard link to the file see the changes. Also, all of the directory entries are updated if the file changes. For example, if the file's size changes, all of the hard links to the file will show the new size.

The security descriptor belongs to the file to which the hard link points. The link itself, being merely a directory entry, has no security descriptor. Thus, if you change the security descriptor of any hard link, you're actually changing the underlying file's security descriptor. All hard links that point to the file will thus allow the newly specified access. There is no way to give a file different security descriptors on a per-hard-link basis.

This function does not modify the security descriptor of the file to be linked to, even if security descriptor information is passed in the lpSecurityAttributes parameter.

Use DeleteFile to delete hard links. You can delete them in any order regardless of the order in which they were created.

Flags, attributes, access, and sharing as specified in CreateFile operate on a per-file basis. That is, if you open a file with no sharing allowed, another application cannot share the file by creating a new hard link to the file.

CreateHardLink does not work over the network redirector.

Note that when you create a hard link on NTFS, the file attribute information in the directory entry is refreshed only when the file is opened or when GetFileInformationByHandle is called with the handle of the file of interest.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, CreateFile, DeleteFile, SECURITY_ATTRIBUTES


DecryptFile

The DecryptFile function decrypts an encrypted file or directory.

BOOL DecryptFile(
  LPCTSTR lpFileName,  // file name
  DWORD dwReserved     // reserved; must be zero
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the file to decrypt.

The caller must have FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access to the file.

dwReserved
Reserved; must be zero.

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

The DecryptFile function requires exclusive access to the file being decrypted, and will fail if another process is using the file. If the file is not encrypted, DecryptFile simply returns a nonzero value, which indicates success.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, CreateFile, EncryptFile


DeleteVolumeMountPoint

The DeleteVolumeMountPoint function unmounts the volume from the specified volume mount point.

BOOL DeleteVolumeMountPoint(
  LPCTSTR lpszVolumeMountPoint  // volume mount point path
);

Parameters

lpszVolumeMountPoint
[in] Pointer to a string that indicates the volume mount point to be unmounted. This may be a root directory (X:\, in which case the DOS drive letter assignment is removed) or a directory on a volume (X:\mnt\). A trailing backslash is required.

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

It is not an error to attempt to unmount a volume from a volume mount point when there is no volume actually mounted at that volume mount point.

For example, see Unmounting a Volume at a Mount Point.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, GetVolumeNameForVolumeMountPoint, GetVolumePathName, SetVolumeMountPoint


EncryptFile

The EncryptFile function encrypts a file or directory. All data streams in a file are encrypted. All new files created in an encrypted directory are encrypted.

BOOL EncryptFile(
  LPCTSTR lpFileName  // file name
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the file or directory to encrypt.

The caller must have FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access to the file.

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

The EncryptFile function requires exclusive access to the file being encrypted, and will fail if another process is using the file.

If the file is already encrypted, EncryptFile simply returns a nonzero value, which indicates success. If the file is compressed, EncryptFile will decompress the file before encrypting it.

To decrypt an encrypted file, use the DecryptFile function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, DecryptFile


EncryptionDisable

The EncryptionDisable function disables or enables encryption of the indicated directory and the files in it. It does not affect encryption of subdirectories below the indicated directory.

BOOL EncryptionDisable(
    LPCWSTR DirPath,  // directory name
    BOOL Disable      // encryption option
);

Parameters

DirPath
[in] Pointer to a null-terminated Unicode string that specifies the name of the directory for which to enable or disable encryption.
Disable
[in] Indicates whether to disable encryption (TRUE) or enable it (FALSE).

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

Under normal circumstances, EncryptFile will not encrypt files and directories with the FILE_ATTRIBUTE_SYSTEM attribute set. It is possible to override the FILE_ATTRIBUTE_SYSTEM attribute and encrypt files. Also, if a file or directory is marked with the FILE_ATTRIBUTE_SYSTEM attribute, it will normally be invisible to the user in directory listings and Windows Explorer directory windows. EncryptionDisable disables encryption of directories and files. It does not affect the visibility of files with the FILE_ATTRIBUTE_SYSTEM attribute set.

If TRUE is passed in, EncryptionDisable will write

[Encryption]
Disable=1

to the Desktop.ini file in the directory (creating it if necessary). If the section already exists but Disable is set to 0, it will be set to 1.

Thereafter, EncryptFile will fail on the directory and the files in it, and the code that GetLastError returns will be ERROR_DIR_EFS_DISALLOWED. This function does not affect encryption of subdirectories within the given directory.

The user can also manually add or edit the above lines in the Desktop.ini file and produce the same effect.

EncryptionDisable affects only FileEncryptionStatus and EncryptFile. After the directory is encrypted, any new files and new subdirectories created without the FILE_ATTRIBUTE_SYSTEM attribute will be encrypted.

If FALSE is passed in, EncryptionDisable will write

[Encryption]
Disable=0

and file encryption is permitted on the files in that directory.

If you try to use EncryptionDisable to set the directory to the state it is already in, the function succeeds but has no effect.

If you try to use EncryptionDisable to disable or enable encryption on a file, the attempt will fail.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, DecryptFile, EncryptFile, FileEncryptionStatus, GetFileAttributes


FileEncryptionStatus

The FileEncryptionStatus function retrieves the encryption status of the specified file.

BOOL FileEncryptionStatus(
  LPCTSTR lpFileName,  // file name
  LPDWORD lpStatus     // encryption status
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the file.
lpStatus
[out] Pointer to a variable that receives the encryption status of the file. This parameter can be one of the following values.
Value | Meaning
FILE_ENCRYPTABLE | The file can be encrypted.
FILE_IS_ENCRYPTED | The file is encrypted.
FILE_SYSTEM_ATTR | The file is a system file. System files cannot be encrypted.
FILE_ROOT_DIR | The file is a root directory. Root directories cannot be encrypted.
FILE_SYSTEM_DIR | The file is a system directory. System directories cannot be encrypted.
FILE_UNKNOWN | The encryption status is unknown. The file may be encrypted.
FILE_SYSTEM_NOT_SUPPORT | The file system does not support file encryption.
FILE_USER_DISALLOWED | Reserved for future use.
FILE_READ_ONLY | The file is a read-only file.

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.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, EncryptFile


FindFirstVolume

The FindFirstVolume function returns the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer.

HANDLE FindFirstVolume(
  LPTSTR lpszVolumeName,   // output buffer
  DWORD cchBufferLength    // size of output buffer
);

Parameters

lpszVolumeName
[out] Pointer to a buffer that receives the unique volume name of the first volume found.
cchBufferLength
[in] Length, in TCHARs, of the buffer to receive the name.

Return Values

If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions.

If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError.

Remarks

The FindFirstVolume function opens a volume search handle and returns information about the first volume found on a computer. After the search handle is established, you can use the FindNextVolume function to search for other volumes. When the search handle is no longer needed, close it by using the FindVolumeClose function.

You should not assume any correlation between the order of volumes returned with these functions and the order of volumes on the computer. In particular, do not assume any correlation between volume order and drive letters as assigned by the BIOS (if any) or the Disk Administrator.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, FindNextVolume, FindVolumeClose


FindFirstVolumeMountPoint

The FindFirstVolumeMountPoint function returns the name of a volume mount point on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the volume mount points on a volume.

HANDLE FindFirstVolumeMountPoint(
  LPTSTR lpszRootPathName,     // volume name
  LPTSTR lpszVolumeMountPoint, // output buffer
  DWORD cchBufferLength        // size of output buffer
);

Parameters

lpszRootPathName
[in] Unique volume name of the volume to scan for volume mount points. A trailing backslash is required.
lpszVolumeMountPoint
[out] Pointer to a buffer that receives the name of the first volume mount point found.
cchBufferLength
[in] Specifies the length, in TCHARs, of the buffer that receives the volume mount point name.

Return Values

If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions.

If the function fails to find a volume mount point on the volume, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError.

Remarks

The FindFirstVolumeMountPoint function opens a mount-point search handle and returns information about the first volume mount point found on the specified volume. After the search handle is established, you can use the FindNextVolumeMountPoint function to search for other volume mount points. When the search handle is no longer needed, close it with the FindVolumeMountPointClose function.

You should not assume any correlation between the order of volume mount points returned by these functions and the order of volume mount points returned by other tools.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, FindNextVolumeMountPoint, FindVolumeMountPointClose


FindNextVolume

The FindNextVolume function continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call.

BOOL FindNextVolume(
  HANDLE hFindVolume,      // volume search handle
  LPTSTR lpszVolumeName,   // output buffer
  DWORD cchBufferLength    // size of output buffer
);

Parameters

hFindVolume
[in] Volume search handle returned by a previous call to the FindFirstVolume function.
lpszVolumeName
[out] Pointer to a string that receives the unique volume name found.
cchBufferLength
[in] Specifies the length, in TCHARs, of the buffer that receives the name.

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. If no matching files can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. In that case, close the search with the FindVolumeClose function.

Remarks

After the search handle is established by calling FindFirstVolume, you can use the FindNextVolume function to search for other volumes.

You should not assume any correlation between the order of volumes returned with these functions and the order of volumes on the computer. In particular, do not assume any correlation between volume order and drive letters as assigned by the BIOS (if any) or the Disk Administrator.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, FindFirstVolume, FindVolumeClose


FindNextVolumeMountPoint

The FindNextVolumeMountPoint function continues a volume mount point search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one volume mount point per call.

BOOL FindNextVolumeMountPoint(
  HANDLE hFindVolumeMountPoint,    // search handle
  LPTSTR lpszVolumeMountPoint,     // output buffer
  DWORD cchBufferLength            // size of output buffer
);

Parameters

hFindVolumeMountPoint
[in] Mount-point search handle returned by a previous call to the FindFirstVolumeMountPoint function.
lpszVolumeMountPoint
[out] Pointer to a string that receives the name of the volume mount point found.
cchBufferLength
[in] Specifies the length, in TCHARs, of the buffer that receives the names.

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. If no matching files can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. In that case, close the search with the FindVolumeMountPointClose function.

Remarks

After the search handle is established by calling FindFirstVolumeMountPoint, you can use the FindNextVolumeMountPoint function to search for other volume mount points.

You should not assume any correlation between the order of volume mount points returned with these functions and the order of volume mount points returned by other tools.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, FindFirstVolumeMountPoint, FindVolumeMountPointClose


FindVolumeClose

The FindVolumeClose function closes the specified volume search handle. The FindFirstVolume and FindNextVolume functions use this search handle to locate volumes.

BOOL FindVolumeClose(
  HANDLE hFindVolume       // search handle
);

Parameters

hFindVolume
[in] Volume search handle to close. This handle must have been previously opened by the FindFirstVolume function.

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

After the FindVolumeClose function is called, the handle hFindVolume cannot be used in subsequent calls to either FindNextVolume or FindVolumeClose.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File Systems Overview, File System Functions, FindFirstVolume, FindNextVolume


FindVolumeMountPointClose

The FindVolumeMountPointClose function closes the specified mount-point search handle. The FindFirstVolumeMountPoint and FindNextVolumeMountPoint functions use this search handle to locate volume mount points on a specified volume.

BOOL FindVolumeMountPointClose(
  HANDLE hFindVolumeMountPoint // search handle
);

Parameters

hFindVolumeMountPoint
[in] Mount-point search handle to close. This handle must have been previously opened by the FindFirstVolumeMountPoint function.

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

After the FindVolumeMountPointClose function is called, the handle hFindVolumeMountPoint cannot be used in subsequent calls to either FindNextVolumeMountPoint or FindVolumeMountPointClose.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

File Systems Overview, File System Functions, FindFirstVolumeMountPoint, FindNextVolumeMountPoint


FreeEncryptionCertificateHashList

The FreeEncryptionCertificateHashList function frees a certificate hash list.

VOID FreeEncryptionCertificateHashList(
  PENCRYPTION_CERTIFICATE_HASH_LIST pHashes  // hash list
);

Parameters

pHashes
[in] Pointer to a certificate hash list structure, ENCRYPTION_CERTIFICATE_HASH_LIST, which was returned by the QueryUsersOnEncryptedFile or QueryRecoveryAgentsOnEncryptedFile function.

Return Values

This function does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE_HASH_LIST, QueryRecoveryAgentsOnEncryptedFile, QueryUsersOnEncryptedFile


GetCompressedFileSize

The GetCompressedFileSize function retrieves the actual number of bytes of disk storage used to store a specified file. If the file is located on a volume that supports compression, and the file is compressed, the value obtained is the compressed size of the specified file. If the file is located on a volume that supports sparse files, and the file is a sparse file, the value obtained is the sparse size of the specified file.

DWORD GetCompressedFileSize(
  LPCTSTR lpFileName,     // file name
  LPDWORD lpFileSizeHigh  // high-order DWORD of file size
);

Parameters

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the file.

Do not specify the name of a file on a nonseeking device, such as a pipe or a communications device, as its file size has no meaning.

lpFileSizeHigh
[out] Pointer to a variable that receives the high-order DWORD of the compressed file size. The function's return value is the low-order DWORD of the compressed file size.

This parameter can be NULL if the high-order DWORD of the compressed file size is not needed. Files less than 4 gigabytes in size do not need the high-order DWORD.

Return Values

If the function succeeds, the return value is the low-order DWORD of the actual number of bytes of disk storage used to store the specified file, and if lpFileSizeHigh is non-NULL, the function puts the high-order DWORD of that actual value into the DWORD pointed to by that parameter. This is the compressed file size for compressed files, the actual file size for noncompressed files.

If the function fails, and lpFileSizeHigh is NULL, the return value is INVALID_FILE_SIZE. To get extended error information, call GetLastError.

If the return value is INVALID_FILE_SIZE and lpFileSizeHigh is non-NULL, an application must call GetLastError to determine whether the function has succeeded (value is NO_ERROR) or failed (value is other than NO_ERROR).

Remarks

An application can determine whether a volume is compressed by calling GetVolumeInformation, then checking the status of the FS_VOL_IS_COMPRESSED flag in the DWORD value pointed to by that function's lpFileSystemFlags parameter.

If the file is not located on a volume that supports compression or sparse files, or if the file is not compressed or a sparse file, the value obtained is the actual file size, the same as the value returned by a call to GetFileSize.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

File Systems Overview, File System Functions, GetFileSize, GetVolumeInformation


GetVolumeInformation

The GetVolumeInformation function retrieves information about a file system and volume whose root directory is specified.

BOOL GetVolumeInformation(
  LPCTSTR lpRootPathName,           // root directory
  LPTSTR lpVolumeNameBuffer,        // volume name buffer
  DWORD nVolumeNameSize,            // length of name buffer
  LPDWORD lpVolumeSerialNumber,     // volume serial number
  LPDWORD lpMaximumComponentLength, // maximum file name length
  LPDWORD lpFileSystemFlags,        // file system options
  LPTSTR lpFileSystemNameBuffer,    // file system name buffer
  DWORD nFileSystemNameSize         // length of file system name buffer
);

Parameters

lpRootPathName
[in] Pointer to a string that contains the root directory of the volume to be described. If this parameter is NULL, the root of the current directory is used. A trailing backslash is required. For example, you would specify \\MyServer\MyShare as \\MyServer\MyShare\, or the C drive as "C:\".
lpVolumeNameBuffer
[out] Pointer to a buffer that receives the name of the specified volume.
nVolumeNameSize
[in] Specifies the length, in TCHARs, of the volume name buffer. This parameter is ignored if the volume name buffer is not supplied.
lpVolumeSerialNumber
[out] Pointer to a variable that receives the volume serial number. This parameter can be NULL if the serial number is not required.

Windows 95/98/Me: If the queried volume is a network drive, the serial number will not be returned.

lpMaximumComponentLength
[out] Pointer to a variable that receives the maximum length, in TCHARs, of a file name component supported by the specified file system. A file name component is that portion of a file name between backslashes.

The value stored in variable pointed to by *lpMaximumComponentLength is used to indicate that long names are supported by the specified file system. For example, for a FAT file system supporting long names, the function stores the value 255, rather than the previous 8.3 indicator. Long names can also be supported on systems that use the NTFS file system.

lpFileSystemFlags
[out] Pointer to a variable that receives flags associated with the specified file system. This parameter can be any combination of the following flags; however, FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED are mutually exclusive.
Value | Meaning
FS_CASE_IS_PRESERVED | The file system preserves the case of file names when it places a name on disk.
FS_CASE_SENSITIVE | The file system supports case-sensitive file names.
FS_UNICODE_STORED_ON_DISK | The file system supports Unicode in file names as they appear on disk.
FS_PERSISTENT_ACLS | The file system preserves and enforces ACLs. For example, NTFS preserves and enforces ACLs, and FAT does not.
FS_FILE_COMPRESSION | The file system supports file-based compression.
FS_VOL_IS_COMPRESSED | The specified volume is a compressed volume; for example, a DoubleSpace volume.
FILE_NAMED_STREAMS | The file system supports named streams.
FILE_READ_ONLY_VOLUME | Whistler: The specified volume is read-only.
FILE_SUPPORTS_ENCRYPTION | The file system supports the Encrypted File System (EFS).
FILE_SUPPORTS_OBJECT_IDS | The file system supports object identifiers.
FILE_SUPPORTS_REPARSE_POINTS | The file system supports reparse points.
FILE_SUPPORTS_SPARSE_FILES | The file system supports sparse files.
FILE_VOLUME_QUOTAS | The file system supports disk quotas.

lpFileSystemNameBuffer
[out] Pointer to a buffer that receives the name of the file system (such as FAT or NTFS).
nFileSystemNameSize
[in] Specifies the length, in TCHARs, of the file system name buffer. This parameter is ignored if the file system name buffer is not supplied.

Return Values

If all the requested information is retrieved, the return value is nonzero.

If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError.

Remarks

If you are attempting to obtain information about a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a compact disc, the system displays a message box asking the user to insert a floppy disk or a compact disc, respectively. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS.

The FS_VOL_IS_COMPRESSED flag is the only indicator of volume-based compression. The file system name is not altered to indicate compression. This flag comes back set on a DoubleSpace volume, for example. With volume-based compression, an entire volume is either compressed or not compressed.

The FS_FILE_COMPRESSION flag indicates whether a file system supports file-based compression. With file-based compression, individual files can be compressed or not compressed.

The FS_FILE_COMPRESSION and FS_VOL_IS_COMPRESSED flags are mutually exclusive; both bits cannot come back set.

The maximum component length value, stored in lpMaximumComponentLength, is the only indicator that a volume supports longer-than-normal FAT (or other file system) file names. The file system name is not altered to indicate support for long file names.

The GetCompressedFileSize function obtains the compressed size of a file. The GetFileAttributes function can determine whether an individual file is compressed.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: 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.

See Also

File Systems Overview, File System Functions, GetCompressedFileSize, GetFileAttributes, SetErrorMode, SetVolumeLabel


GetVolumeNameForVolumeMountPoint

The GetVolumeNameForVolumeMountPoint function takes a volume mount point or root directory and returns the corresponding unique volume name.

BOOL GetVolumeNameForVolumeMountPoint(
  LPCTSTR lpszVolumeMountPoint, // volume mount point or directory
  LPTSTR lpszVolumeName,        // volume name buffer
  DWORD cchBufferLength         // size of volume name buffer
);

Parameters

lpszVolumeMountPoint
[in] Pointer to a string that contains either the path of a volume mount point with a trailing backslash (\) or a drive letter indicating a root directory in the form "D:\".
lpszVolumeName
[out] Pointer to a string that receives the volume name. This name is a unique volume name of the form "\\?\Volume{GUID}\" where GUID is the GUID that identifies the volume.
cchBufferLength
[in] Specifies the length, in TCHARs, of the output buffer. A reasonable size for the buffer to accommodate the largest possible volume name is 50 characters.

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

The lpszVolumeMountPoint input string may be a drive letter with appended backslash (\), such as "D:\". Alternatively, it may be a path to a volume mount point, again with appended backslash (\), such as "c:\mnt\edrive\".

Use GetVolumeNameForVolumeMountPoint to obtain unique volume names for use with other functions that work with volume mount points and volume mounting. For more information, see Unique Volume Names.

For example, see Enumerating Mount Points.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, DeleteVolumeMountPoint, GetVolumePathName, SetVolumeMountPoint


GetVolumePathName

The GetVolumePathName function retrieves the volume mount point at which the specified path is mounted.

BOOL GetVolumePathName(
  LPCTSTR lpszFileName,         // file path
  LPTSTR lpszVolumePathName,    // volume mount point
  DWORD cchBufferLength         // size of buffer
);

Parameters

lpszFileName
[in] Specifies the input path string. Both absolute and relative file and directory names, such as ".", are acceptable in this path.
lpszVolumePathName
[out] Pointer to a string that receives the volume mount point for the input path.
cchBufferLength
[in] Specifies the length, in TCHARs, of the output buffer.

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

Passed a specified path, GetVolumePathName returns the path to the volume mount point. In other words, it returns the root of the volume where the end point of the specified path resides.

For example, assume you have volume D mounted at C:\Mnt\Ddrive and volume E mounted at C:\Mnt\Ddrive\Mnt\Edrive. Assume you have a file with the path E:\Dir\Subdir\MyFile. If you pass GetVolumePathName the input string "C:\Mnt\Ddrive\Mnt\Edrive\Dir\Subdir\MyFile", it returns the output path "C:\Mnt\Ddrive\Mnt\Edrive".

The length of the path returned by this call always is less than or equal to that of the path passed in. A slower but safer way to set the size of the return buffer is to call the GetFullPathName function and then make sure that the buffer is at least as big as the full path GetFullPathName returns.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, DeleteVolumeMountPoint, GetFullPathName, GetVolumeNameForVolumeMountPoint, SetVolumeMountPoint


GetVolumePathNamesForVolumeName

[This is preliminary documentation and subject to change.]

The GetVolumePathNamesForVolumeName function retrieves a list of path names for the specified volume name.

BOOL GetVolumePathNamesForVolumeName(
  LPCTSTR lpszVolumeName,
  LPTSTR lpszVolumePathNames,
  DWORD cchBufferLength,
  PDWORD lpcchReturnLength
);

Parameters

lpszVolumeName
[in] Pointer to a string that specifies the volume name.
lpszVolumePathNames
[out] Pointer to a buffer that receives the list of volume path names. The list is an array of null-terminated strings terminated by an additional NULL character. If the buffer is not large enough to hold the complete list, the buffer holds as much of the list as possible.
cchBufferLength
[in] Size of the lpszVolumePathNames buffer, in TCHARs.
lpcchReturnLength
[out] If the call is successful, this parameter is the number of TCHARs copied to the lpszVolumePathNames buffer. Otherwise, this parameter is the size of the buffer required to hold the complete list, in TCHARs.

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. If the buffer is not large enough to hold the complete list, the error code is ERROR_MORE_DATA and the lpcchReturnLength parameter receives the required buffer size.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

File Systems Overview, File System Functions


QueryRecoveryAgentsOnEncryptedFile

The QueryRecoveryAgentsOnEncryptedFile function retrieves a list of recovery agents for the specified file.

DWORD QueryRecoveryAgentsOnEncryptedFile(
  LPCWSTR lpFileName,                                 // file name
  PENCRYPTION_CERTIFICATE_HASH_LIST *pRecoveryAgents  // hash list
);

Parameters

lpFileName
[in] Pointer to a null-terminated Unicode string that specifies the name of the file to query.
pRecoveryAgents
[out] Receives a list of recovery agents, represented by a ENCRYPTION_CERTIFICATE_HASH_LIST structure.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error code. For a complete list of error codes, see Error Codes or the Platform SDK header file WinError.h.

Remarks

When the list of recovery agents is no longer needed, free it by calling the FreeEncryptionCertificateHashList function.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE_HASH_LIST, FreeEncryptionCertificateHashList


QueryUsersOnEncryptedFile

The QueryUsersOnEncryptedFile function retrieves a list of users for the specified file.

DWORD QueryUsersOnEncryptedFile(
  LPCWSTR lpFileName,                        // file name
  PENCRYPTION_CERTIFICATE_HASH_LIST *pUsers  // hash list
);

Parameters

lpFileName
[in] Pointer to a null-terminated Unicode string that specifies the name of the file to query.
pUsers
[out] Receives a list of users, represented by a ENCRYPTION_CERTIFICATE_HASH_LIST structure.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error code. For a complete list of error codes, see Error Codes or the Platform SDK header file WinError.h.

Remarks

When the list of users is no longer needed, call the FreeEncryptionCertificateHashList function to free the list.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE_HASH_LIST, FreeEncryptionCertificateHashList


RemoveUsersFromEncryptedFile

The RemoveUsersFromEncryptedFile function removes specified certificate hashes from a specified file.

DWORD RemoveUsersFromEncryptedFile(
  LPCWSTR lpFileName,                        // file name
  PENCRYPTION_CERTIFICATE_HASH_LIST pHashes  // hash list
);

Parameters

lpFileName
[in] Pointer to a null-terminated Unicode string that specifies the name of the file.
pHashes
[in] Pointer to an ENCRYPTION_CERTIFICATE_HASH_LIST structure that contains a list of certificate hashes to be removed from the file.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error code. For a complete list of error codes, see Error Codes or the Platform SDK header file WinError.h.

Remarks

The RemoveUsersFromEncryptedFile function removes the specified certificate hashes if they exist in the specified file. If any of the certificate hashes are not found in the specified file, they are ignored and no error code is returned.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE_HASH_LIST


SetUserFileEncryptionKey

The SetUserFileEncryptionKey function sets the user's current key to the specified certificate.

DWORD SetUserFileEncryptionKey(
  PENCRYPTION_CERTIFICATE pEncryptionCertificate  // certificate
);

Parameters

pEncryptionCertificate
[in] Pointer to a certificate that will be the user's key. This parameter is a pointer to an ENCRYPTION_CERTIFICATE structure.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a Win32 error code. For a complete list of error codes, see Error Codes or the Platform SDK header file WinError.h.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

File Systems Overview, File System Functions, ENCRYPTION_CERTIFICATE


SetVolumeMountPoint

The SetVolumeMountPoint function mounts the specified volume at the specified volume mount point.

BOOL SetVolumeMountPoint(
  LPCTSTR lpszVolumeMountPoint, // mount point
  LPCTSTR lpszVolumeName        // volume to be mounted
);

Parameters

lpszVolumeMountPoint
[in] Pointer to a string that indicates the volume mount point where the volume is to be mounted. This may be a root directory (X:\) or a directory on a volume (X:\mnt\). The string must end with a trailing backslash ('\').
lpszVolumeName
[in] Pointer to a string that indicates the volume to be mounted. This string must be a unique volume name of the form "\\?\Volume{GUID}\" where GUID is a GUID that identifies the volume. The \\?\ turns off path parsing and is ignored as part of the path, as discussed in Path Lengths. For example, "\\?\C:\myworld\private" is seen as "C:\myworld\private".

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

It is not an error to attempt to mount a volume at a volume mount point at which a volume is already mounted. In this case, the system unmounts the preceding volume without sending notifications before attempting to mount the new volume.

It is an error to attempt to mount a volume on a directory that has any files or subdirectories in it. This error occurs for system and hidden directories as well as other directories, and it occurs for system and hidden files.

For example, see Mounting a Volume at a Mount Point.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

File Systems Overview, File System Functions, DeleteVolumeMountPoint, GetVolumeNameForVolumeMountPoint, GetVolumePathName


File System Control Codes

The following are defragmentation control codes.

Value | Meaning
FSCTL_GET_RETRIEVAL_POINTERS | Get information about a file's cluster use.
FSCTL_GET_VOLUME_BITMAP | Get a bitmap of cluster allocation.
FSCTL_MOVE_FILE | Move all or part of a file from one set of clusters to another within a volume.

The following control codes are used with file compression.

Value | Meaning
FSCTL_GET_COMPRESSION | Obtains the compression state of a file or directory
FSCTL_SET_COMPRESSION | Sets the compression state of a file or directory.

The following control codes are used with NTFS change journals.

Value | Meaning
FSCTL_CREATE_USN_JOURNAL | Creates an NTFS change journal stream on a target volume or modifies an existing change journal stream.
FSCTL_DELETE_USN_JOURNAL | Deletes the NTFS change journal on a volume or awaits notification of deletion of an NTFS change journal.
FSCTL_ENUM_USN_DATA | Creates an enumeration that lists the NTFS change journal entries between two specified boundaries.
FSCTL_MARK_HANDLE | Marks a specified file or directory and its NTFS change journal record with information about changes to that file or directory.
FSCTL_QUERY_USN_JOURNAL | Queries for information on the current NTFS change journal, its records, and its capacity.
FSCTL_READ_USN_JOURNAL | Returns to the calling process the set of NTFS change journal records between two specified USN values.
FSCTL_WRITE_USN_CLOSE_RECORD | Generates a record in the change journal stream for the input file. This record will have the USN_REASON_CLOSE flag.

The following control codes are used with opportunistic locks.

Value | Meaning
FSCTL_OPBATCH_ACK_CLOSE_PENDING | Notifies a server that a client application is about to close a file. An application uses this operation following notification that an opportunistic lock on the file is about to be broken.
FSCTL_OPLOCK_BREAK_ACK_NO_2 | Responds to notification that an opportunistic lock on a file is about to be broken. An application uses this operation to loose all opportunistic locks on the file but keep the file open.
FSCTL_OPLOCK_BREAK_ACKNOWLEDGE | Responds to notification that an exclusive opportunistic lock on a file is about to be broken. An application uses this operation to indicate that the file should receive a level 2 opportunistic lock.
FSCTL_OPLOCK_BREAK_NOTIFY | Allows the calling application to wait for completion of an opportunistic lock break.
FSCTL_REQUEST_BATCH_OPLOCK | Requests a batch opportunistic lock on a file.
FSCTL_REQUEST_FILTER_OPLOCK | Requests a filter opportunistic lock on a file.
FSCTL_REQUEST_OPLOCK_LEVEL_1 | Requests a level 1 opportunistic lock on a file.
FSCTL_REQUEST_OPLOCK_LEVEL_2 | Requests a level 2 opportunistic lock on a file.

The following control codes are used with reparse points.

Value | Meaning
FSCTL_DELETE_REPARSE_POINT | Deletes a reparse point for a file or directory.
FSCTL_GET_REPARSE_POINT | Returns reparse point data for a file or directory.
FSCTL_SET_REPARSE_POINT | Sets a reparse point on a file or directory.

The following control codes are used with sparse files.

Value | Meaning
FSCTL_QUERY_ALLOCATED_RANGES | Scans a file for ranges of the file for which disk space is allocated.
FSCTL_SET_SPARSE | Marks a file as a sparse file.
FSCTL_SET_ZERO_DATA | Sets a range of a files bytes to zeroes.


File System Interfaces

The following interfaces are used with file systems.

IDiskQuotaControl
IDiskQuotaEvents
IDiskQuotaUser
IDiskQuotaUserBatch
IEnumDiskQuotaUsers


IDiskQuotaControl

The IDiskQuotaControl interface provides methods for controlling the disk quota facilities of a single NTFS volume. The client can query and set volume-specific quota attributes through IDiskQuotaControl. The client can also enumerate all per-user quota entries on the volume. A client instantiates this interface by calling the CoCreateInstance function using the class identifier CLSID_DiskQuotaControl.

Virtual function table

IUnknown Methods

QueryInterface
AddRef
Release

IDiskQuotaControl Methods

Initialize
SetQuotaState
GetQuotaState
SetQuotaLogFlags
GetQuotaLogFlags
SetDefaultQuotaThreshold
GetDefaultQuotaThreshold
GetDefaultQuotaThresholdText
SetDefaultQuotaLimit
GetDefaultQuotaLimit
GetDefaultQuotaLimitText
AddUserSid
AddUserName
DeleteUser
FindUserSid
FindUserName
CreateEnumUsers
CreateUserBatch
InvalidateSidNameCache
GiveUserNameResolutionPriority
ShutdownNameResolution

Remarks

The disk quota control object also implements the IConnectionPointContainer interface to service the IDiskQuotaEvents interface.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces


IDiskQuotaControl::AddUserName

Adds a new quota entry on the volume for the specified user. The user is identified by domain and account name.

HRESULT AddUserName(
  LPCWSTR pszLogonName,
  DWORD fNameResolution,
  PDISKQUOTA_USER *ppUser
);

Parameters

pszLogonName
Pointer to the user's account logon name string.
fNameResolution
Indicates how the user account information is to be obtained. The volume's quota information identifies users by SID. The user account information (such as container, logon name, and display name) must be obtained from the network domain controller, or the local computer if it is not on a network. This parameter can be one of the following values.
Value | Meaning
DISKQUOTA_USERNAME_RESOLVE_NONE | Do not resolve user account information.
DISKQUOTA_USERNAME_RESOLVE_SYNC | Resolve user account information synchronously. AddUserName returns when the information is resolved. If the information exists in the disk quota SID cache, it is returned immediately. Otherwise, the method must locate the information. This can take several seconds.
DISKQUOTA_USERNAME_RESOLVE_ASYNC | Resolve user account information asynchronously. AddUserName returns immediately. The caller must implement the IDiskQuotaEvents interface to receive notification when the information is available. If the information was cached during a previous request, notification occurs as soon as the object is serviced. Otherwise, the method obtains the information from the network domain controller, then notifies IDiskQuotaEvents.

ppUser
Pointer to receive the IDiskQuotaUser interface pointer to the newly created quota user object.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
S_OK | Success.
S_FALSE | User already exists. Not added.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
ERROR_USER_UNKNOWN | The specified user name is unknown.
E_INVALIDARG | A pointer parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

The NTFS file system automatically creates a user quota entry when a user first writes to the volume. Entries that are created automatically are assigned the default warning threshold and hard quota limit values for the volume. This method allows you to create a user quota entry before a user has written information to the volume. Therefore, you can pre-assign a warning threshold or hard quota limit value different than the volume default settings.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::AddUserSid

Adds a new quota entry on the volume for the specified user. The user is identified by security identifier (SID).

HRESULT AddUserSid(
  PSID pUserSid,
  DWORD fNameResolution,
  PDISKQUOTA_USER *ppUser
);

Parameters

pUserSid
Pointer to a buffer containing the user's SID.
fNameResolution
Indicates how the user account information is to be obtained. The volume's quota information identifies users by SID. The user account information (such as domain name, account name, and full name) must be obtained from the network domain controller, or the local computer if it is not on a network. This parameter can be one of the following values.
Value | Meaning
DISKQUOTA_USERNAME_RESOLVE_NONE | Do not resolve user account information.
DISKQUOTA_USERNAME_RESOLVE_SYNC | Resolve user account information synchronously. AddUserSid returns when the information is resolved. If the information exists in the disk quota SID cache, it is returned immediately. Otherwise, the method must locate the information. This can take several seconds.
DISKQUOTA_USERNAME_RESOLVE_ASYNC | Resolve user account information asynchronously. AddUserSid returns immediately. The caller must implement the IDiskQuotaEvents interface to receive notification when the information is available. If the information was cached during a previous request, notification occurs as soon as the object is serviced. Otherwise, the method obtains the information from the network domain controller, then notifies IDiskQuotaEvents.

ppUser
Pointer to receive the IDiskQuotaUser interface pointer to the newly created quota user object.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_INVALID_SID | The specified SDI is unknown.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pUserSid or ppUser parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

The NTFS file system automatically creates a user quota entry when a user first writes to the volume. Entries that are created automatically are assigned the default warning threshold and hard quota limit values for the volume. This method allows you to create a user quota entry before a user has written information to the volume. Therefore, you can pre-assign a warning threshold or hard quota limit value different than the volume default settings.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::CreateEnumUsers

Creates an enumerator object for enumerating quota users on the volume. The newly created object implements the IEnumDiskQuotaUsers interface.

HRESULT CreateEnumUsers(
  PSID *rgpUserSids,
  DWORD cpSids,
  DWORD fNameResolution,
  PENUM_DISKQUOTA_USERS *ppEnum
);

Parameters

rgpUserSids
Array of security identifier (SID) pointers representing the user objects to be included in the enumeration. If this value is NULL, all user entries are enumerated.
cpSids
Number of items in the rgpUserSids array. Ignored if rgpUserSids is NULL.
fNameResolution
Indicates how the user account information is to be obtained. The volume's quota information identifies users by SID. The user account information (such as domain name, account name, and full name) must be obtained from the network domain controller, or the local computer if it is not on a network. This parameter can be one of the following values.
Value | Meaning
DISKQUOTA_USERNAME_RESOLVE_NONE | Do not resolve user account information.
DISKQUOTA_USERNAME_RESOLVE_SYNC | Resolve user account information synchronously. The IEnumDiskQuotaUsers::Next method returns when the information is resolved. If the information exists in the disk quota SID cache, it is returned immediately. Otherwise, the method must locate the information. This can take several seconds.
DISKQUOTA_USERNAME_RESOLVE_ASYNC | Resolve user account information asynchronously. The IEnumDiskQuotaUsers::Next method returns immediately. The caller must implement the IDiskQuotaEvents interface to receive notification when the information is available. If the information was cached during a previous request, notification occurs as soon as the object is serviced. Otherwise, the method obtains the information from the network domain controller, then notifies IDiskQuotaEvents.

ppEnum
Pointer to a pointer to the IEnumDiskQuotaUsers enumerator.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The ppEnum parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::CreateUserBatch

Creates a batching object for optimizing updates to the quota settings of multiple users simultaneously.

HRESULT CreateUserBatch(
  PDISKQUOTA_USER_BATCH *ppBatch
);

Parameters

ppBatch
Pointer to receive the IDiskQuotaUserBatch interface pointer.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The ppBatch parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::DeleteUser

Removes a user entry from the volume quota information file, if the user's charged quota amount is zero bytes.

HRESULT DeleteUser(
  PDISKQUOTA_USER pUser
);

Parameters

pUser
Pointer to the IDiskQuotaUser interface of the user whose quota record is marked for deletion.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_FILE_EXISTS | The user owns files on the volume.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pUser parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

This method does not actually remove the quota entry from the volume. It marks the entry for deletion. NTFS performs the actual deletion at a later time. Following a call to IDiskQuotaControl::DeleteUser, the IDiskQuotaUser interface is still active. This method does not delete the user object from memory. To release the user object, call IUnknown::Release.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::FindUserName

Locates a specific entry in the volume quota information. The user's account logon name is used as the search key.

HRESULT FindUserName(
  LPCWSTR pszLogonName,
  PDISKQUOTA_USER *ppUser
);

Parameters

pszLogonName
Pointer to the user's account logon name.
ppUser
Pointer to receive the IDiskQuotaUser interface pointer to the quota user object.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_INVALID_SID | The SID for the user is invalid.
ERROR_NONE_MAPPED | There is no mapping available for the SID.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pUserSid or ppUser parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

This method will return a user object even if there is no quota record for the user in the quota file. This is consistent with the idea of automatic user addition and default quota settings. If there is currently no quota entry for the requested user, and the user would be added to the quota file if he were to request disk space, the returned user object will have warning threshold and hard quota limits equal to the volume default settings.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::FindUserSid

Locates a specific user entry in the volume quota information. The user's security identifier (SID) is used as the search key.

HRESULT FindUserSid(
  PSID pUserSid,
  DWORD fNameResolution,
  PDISKQUOTA_USER *ppUser
);

Parameters

pUserSid
Pointer to the user's SID.
fNameResolution
Indicates how the user account information is to be obtained. The volume's quota information identifies users by SID. The user account information (such as domain name, account name, and full name) must be obtained from the network domain controller, or the local computer if it is not on a network. This parameter can be one of the following values.
Value | Meaning
DISKQUOTA_USERNAME_RESOLVE_NONE | Do not resolve user account information.
DISKQUOTA_USERNAME_RESOLVE_SYNC | Resolve user account information synchronously. FindUserSid returns when the information has been resolved. If the information exists in the disk quota SID cache, it is returned immediately. Otherwise, the method must locate the information. This can take several seconds.
DISKQUOTA_USERNAME_RESOLVE_ASYNC | Resolve user account information asynchronously. FindUserSid returns immediately. The caller must implement the IDiskQuotaEvents interface to receive notification when the information is available. If the information was cached during a previous request, notification occurs as soon as the object is serviced. Otherwise, the method obtains the information from the network domain controller, then notifies IDiskQuotaEvents.

ppUser
Pointer to receive the IDiskQuotaUser interface pointer to the quota user object.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
ERROR_INVALID_SID | The SID for the user is invalid.
E_INVALIDARG | The pUserSid or ppUser parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

This method will return a user object even if there is no quota record for the user in the quota file. This is consistent with the idea of automatic user addition and default quota settings. If there is currently no quota entry for the requested user, and the user would be added to the quota file if he were to request disk space, the returned user object will have warning threshold and hard quota limits equal to the volume default settings.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetDefaultQuotaLimit

Retrieves the default quota limit for the volume. This limit is applied automatically to new users of the volume.

HRESULT GetDefaultQuotaLimit(
  PLONGLONG pllLimit
);

Parameters

pllLimit
Pointer to the variable to receive the quota limit.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pllLimit parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetDefaultQuotaLimitText

Retrieves the default quota limit for the volume. This limit is applied automatically to new users of the volume. The limit is expressed as a text string, for example "10.5 MB". If the volume has no limit, the string returned is "No Limit" (localized). If the buffer is too small, it is truncated to fit the buffer.

HRESULT GetDefaultQuotaLimitText(
  LPWSTR pszText,
  DWORD cchText
);

Parameters

pszText
Pointer to the buffer to receive the text string.
cchText
Size of the buffer, in characters.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pszText parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetDefaultQuotaThreshold

Retrieves the default quota warning threshold for the volume. This threshold is applied automatically to new users of the volume.

HRESULT GetDefaultQuotaThreshold(
  PLONGLONG pllThreshold
);

Parameters

pllThreshold
Pointer to the variable to receive the default warning threshold value, in bytes.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pllThreshold parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetDefaultQuotaThresholdText

Retrieves the default warning threshold for the volume. This threshold is expressed as a text string, for example "10.5 MB". If the volume does not have a threshold, the string returned is "No Limit" (localized). If the buffer is too small, the string is truncated to fit the buffer.

HRESULT GetDefaultQuotaThresholdText(
  LPWSTR pszText,
  DWORD cchText
);

Parameters

pszText
Pointer to the buffer to receive the text string.
cchText
Size of the buffer, in characters.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pszText parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetQuotaLogFlags

Retrieves the flags that control the logging of user-related quota events on the volume. Logging makes an entry in the volume server's event log.

HRESULT GetQuotaLogFlags(
  LPDWORD pdwFlags
);

Parameters

pdwFlags
Pointer to a variable to receive the volume's quota logging flags. Use the following macros to retrieve the contents of the flag value.
Flag | Meaning
DISKQUOTA_IS_LOGGED_USER_THRESHOLD | If set, an event log entry will be created when the user exceeds his assigned warning threshold.
DISKQUOTA_IS_LOGGED_USER_LIMIT | If set, an event log entry will be created when the user exceeds his assigned hard quota limit.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pdwFlags parameter is incorrect.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GetQuotaState

Retrieves a set of flags describing the state of the quota system.

HRESULT GetQuotaState(
  LPDWORD pdwState
);

Parameters

pdwState
Pointer to a variable to receive the quota state flags. This parameter can be one or more of the following flags.
Flag | Meaning
DISKQUOTA_STATE_DISABLED | Quotas are not enabled on the volume.
DISKQUOTA_STATE_TRACK | Quotas are enabled but the limit value is not being enforced. Users may exceed their quota limit.
DISKQUOTA_STATE_ENFORCE | Quotas are enabled and the limit value is enforced. Users cannot exceed their quota limit.
DISKQUOTA_FILESTATE_INCOMPLETE | The volume's quota information is out of date. Quotas are probably disabled.
DISKQUOTA_FILESTATE_REBUILDING | The volume is rebuilding its quota information.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The pdwState parameter is incorrect.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::GiveUserNameResolutionPriority

Promotes the specified user object to the head of the queue so that it is next in line for resolution. By default, quota user objects are serviced in the order in which they were placed in the queue.

This method is applicable only when asynchronous name resolution is used.

HRESULT GiveUserNameResolutionPriority(
  PDISKQUOTA_USER pUser
);

Parameters

pUser
Pointer to the IDiskQuotaUser interface.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
S_FALSE | Quota user object not in the resolver queue.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::Initialize

Initializes a new QuotaControl object by opening the NTFS volume with the requested access rights. The return value indicates whether the volume supports NTFS disk quotas and whether the caller has sufficient access rights.

HRESULT Initialize(
  LPCWSTR pszPath,
  BOOL bReadWrite
);

Parameters

pszPath
Specifies the path to the volume root.
bReadWrite
If this value is TRUE, the volume is opened in read/write mode. If this value is FALSE, the volume is opened in read-only mode.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_BAD_PATHNAME | The requested path name is invalid.
ERROR_FILE_NOT_FOUND | The requested file or object was not found.
ERROR_INITIALIZED | The controller object has already been initialized. Multiple initialization is not allowed.
ERROR_INVALID_NAME | The requested file path is invalid.
ERROR_NOTSUPPORTED | The file system does not support quotas.
ERROR_PATH_NOT_FOUND | The requested file path was not found.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::InvalidateSidNameCache

Invalidates the contents of the system's SID-to-name cache so subsequent requests for new user objects (IEnumDiskQuotaUsers::Next, IDiskQuotaControl::FindUserSid and IDiskQuotaControl::FindUserName) must obtain user names from the network domain controller. As names are obtained, they are cached.

HRESULT InvalidateSidNameCache(void);

Parameters

This method has no parameters.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | An unexpected exception occurred.
E_FAIL | The SID-to-name cache is not available or could not be exclusively locked.

Remarks

In general, there is no reason to call this method. It is included to provide a method for programmatically refreshing the entire SID-to-name cache.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::SetDefaultQuotaLimit

Modifies the default quota limit. This limit is applied automatically to new users of the volume.

HRESULT SetDefaultQuotaLimit(
  LONGLONG llLimit
);

Parameters

llLimit
The value for the default quota limit, in bytes.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::SetDefaultQuotaThreshold

Modifies the default warning threshold. This threshold is applied automatically to new users of the volume.

HRESULT SetDefaultQuotaThreshold(
  LONGLONG llThreshold
);

Parameters

llThreshold
Specifies the default warning threshold value, in bytes.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::SetQuotaLogFlags

Controls the logging of user-related quota events on the volume. Logging makes an entry in the volume server system's event log.

HRESULT SetQuotaLogFlags(
  DWORD dwFlags
);

Parameters

dwFlags
Specifies the log flags to be applied to the volume. Use the following macros to set the proper bits in the dwFlags parameter.
Macro | Meaning
DISKQUOTA_SET_LOG_USER_THRESHOLD | Turn on/off logging of user warning threshold violations. If set, an event log entry will be created when the user exceeds his assigned warning threshold.
DISKQUOTA_SET_LOG_USER_LIMIT | Turn on/off logging of user quota limit violations. If set, an event log entry will be created when the user exceeds his assigned hard quota limit.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::SetQuotaState

Sets the state of the quota system. Not all state attributes can be modified. The enable, track, and enforce attributes can be modified.

HRESULT SetQuotaState(
  DWORD dwState
);

Parameters

dwState
Specifies the state to be applied to the volume. Use the following macros to set the proper bits in the dwState parameter.
Macro | Enable | Track | Enforce
DISKQUOTA_SET_DISABLED | No | No | No
DISKQUOTA_SET_TRACKED | Yes | Yes | No
DISKQUOTA_SET_ENFORCED | Yes | Yes | Yes

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_NOT_READY | The DiskQuotaControl object is not initialized.
E_INVALIDARG | The dwState parameter is incorrect.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaControl::ShutdownNameResolution

The SID-to-name resolver translates user security identifiers (SID) to user names. It runs as a background thread. When a quota control object is destroyed, this thread automatically terminates. The final call to the IUnknown::Release method terminates the thread. This is normally all that is required. If you finish with the quota control object, but it is not ready to be destroyed (there are other open reference counts), call this method to terminate the background thread before the object is destroyed.

HRESULT ShutdownNameResolution(void);

Parameters

This method has no parameters.

Return Values

This method returns NOERROR.

Remarks

Asynchronous name resolution will also cease after the thread terminates. A subsequent call to the following methods may recreate the SID-to-name resolver thread:

IDiskQuotaControl::AddUserName
IDiskQuotaControl::AddUserSid
IDiskQuotaControl::CreateEnumUsers
IDiskQuotaControl::FindUserName
IDiskQuotaControl::FindUserSid

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaControl


IDiskQuotaEvents

A client must implement the IDiskQuotaEvents interface as an event sink to receive quota-related event notifications. Its methods are called by the system whenever significant quota events have occurred. Currently, the only event supported is the asynchronous resolution of user account name information.

Virtual Function Table

IUnknown Methods

QueryInterface
AddRef
Release

IDiskQuotaEvents Methods

OnUserNameChanged

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces


IDiskQuotaEvents::OnUserNameChanged

Notifies the client's connection sink whenever a user's SID has been asynchronously resolved. If IDiskQuotaUser::GetAccountStatus returns DISKQUOTA_USER_ACCOUNT_RESOLVED, the user's account container name, logon name, and display name strings are available in the quota user object.

HRESULT OnUserNameChanged(
  PDISKQUOTA_USER pUser
);

Parameters

pUser
Pointer to the IDiskQuotaUser interface for the quota user object. It is not necessary to call Release on this pointer. The DiskQuotaControl object controls the lifetime of the user object.

Return Values

The return value is ignored.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaEvents


IDiskQuotaUser

The IDiskQuotaUser interface represents a single user quota entry in the volume quota information file. Through this interface, you can query and modify user-specific quota information on an NTFS volume. This interface is instantiated using IEnumDiskQuotaUsers, IDiskQuotaControl::FindUserSid, IDiskQuotaControl::FindUserName, IDiskQuotaControl::AddUserSid or IDiskQuotaControl::AddUserName.

Virtual Function Table

IUnknown Methods

QueryInterface
AddRef
Release

IDiskQuotaUser Methods

GetID
GetName
GetSidLength
GetSid
GetQuotaThreshold
GetQuotaThresholdText
GetQuotaLimit
GetQuotaLimitText
GetQuotaUsed
GetQuotaUsedText
GetQuotaInformation
SetQuotaThreshold
SetQuotaLimit
Invalidate
GetAccountStatus

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces


IDiskQuotaUser::GetAccountStatus

Retrieves the status of the user object's account. User information is identified in the quota system by user security identifier (SID). This SID must resolve to a user account for the user's account name information to be retrieved. To determine why a user's name strings are not available, use the status information.

HRESULT GetAccountStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus
Pointer to receive the user's account status. The status value can be one of the following.
Value | Meaning
DISKQUOTA_USER_ACCOUNT_RESOLVED | The SID was resolved to a user account. Names are available through IDiskQuotaUser::GetName.
DISKQUOTA_USER_ABLE | The user account is unavailable at this time. The network domain controller may not be available. Name information is not available.
DISKQUOTA_USER_ACCOUNT_DELETED | The user account was deleted from the domain. Name information is not available.
DISKQUOTA_USER_ACCOUNT_INVALID | The user account is invalid. Name information is not available.
DISKQUOTA_USER_ACCOUNT_UNKNOWN | The user account is unknown. Name information is not available.
DISKQUOTA_USER_ACCOUNT_UNRESOLVED | The SID has not been resolved to a user account.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
E_INVALIDARG | The pdwStatus parameter is NULL.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetID

Retrieves a unique identifier (ID) number for the DiskQuotaUser object. This ID is unique only within the process. It can be used to identify a user object in a set of user objects if the programming language you are using does not support pointers.

HRESULT GetID(
  ULONG *pulID
);

Parameters

pulID
Pointer to the name strings associated with the disk quota user.

Return Values

This method returns NOERROR.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetName

Retrieves the name strings associated with a disk quota user.

HRESULT GetName(
  LPWSTR pszAccountContainer,
  DWORD cchAccountContainer,
  LPWSTR pszLogonName,
  DWORD cchLogonName,
  LPWSTR pszDisplayName,
  DWORD cchDisplayName
);

Parameters

pszAccountContainer
Pointer to the buffer to receive the name of the user's account container. This value can be NULL. For Windows NT 4.0 accounts, or for other accounts on without directory service information, this string is simply the domain name. For accounts with directory service information available, this string is a canonical name with the terminating object name removed.
cchAccountContainer
Size of the account container buffer, in characters. Ignored if pszAccountContainer is NULL.
pszLogonName
Pointer to the buffer to receive the name the user specified to log on the computer. This value can be NULL. The format of the name returned depends on whether directory service information is available.
cchLogonName
Size of the logon name buffer, in characters. Ignored if pszLogonName is NULL.
pszDisplayName
Pointer to the buffer to receive the display name for the quota user. This value can be NULL. If the information is not available, the string returned is of zero length.
cchDisplayName
Size of the display-name buffer, in characters. Ignored if pszDisplayName is NULL.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaInformation

Retrieves the values for the user's warning threshold, hard quota limit, and quota used.

HRESULT GetQuotaInformation(
  LPVOID pbQuotaInfo,
  DWORD cbQuotaInfo
);

Parameters

pbQuotaInfo
Pointer to the DISKQUOTA_USER_INFORMATION structure to receive the quota information.
cbQuotaInfo
Size of the quota information structure, in bytes.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pQuotaInfo parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaLimit

Retrieves the user's quota limit value on the volume. The limit is set as the maximum amount of disk space available to the volume user.

HRESULT GetQuotaLimit(
  PLONGLONG pllLimit
);

Parameters

pllLimit
Pointer to the variable to receive the limit value. If this value is -1, the user has a unlimited quota.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pllLimit parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaLimitText

Retrieves the user's quota limit for the volume. This limit is expressed as a text string, for example "10.5 MB". If the user has no quota limit, the string returned is "No Limit" (localized). If the destination buffer is too small, the string is truncated to fit the buffer.

HRESULT GetQuotaLimitText(
  LPWSTR pszText,
  DWORD cchText
);

Parameters

pszText
Pointer to the buffer to receive the text string.
cchText
Size of the buffer, in characters.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pszText parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaThreshold

Retrieves the user's warning threshold value on the volume. The threshold is an arbitrary value set by the volume's quota administrator. You can use it to identify users who are approaching their hard quota limit.

HRESULT GetQuotaThreshold(
  PLONGLONG pllThreshold
);

Parameters

pllThreshold
Pointer to a variable to receive the warning threshold value.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pllThreshold parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaThresholdText

Retrieves the user's warning threshold for the volume. This threshold is expressed as a text string, for example "10.5 MB". If the user's threshold is unlimited, the string returned is "No Limit" (localized). If the destination buffer is too small, the string is truncated to fit the buffer.

HRESULT GetQuotaThresholdText(
  LPWSTR pszText,
  DWORD cchText
);

Parameters

pszText
Pointer to the buffer to receive the text string.
cchText
Size of the destination buffer, in characters.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pszText parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaUsed

Retrieves the user's quota used value on the volume. This is the amount of information stored on the volume by the user. Note that this is the amount of uncompressed information. Therefore, the use of NTFS compression does not affect this value.

HRESULT GetQuotaUsed(
  PLONGLONG pllUsed
);

Parameters

pllUsed
Pointer to the variable to receive the quota used value.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pllUsed parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetQuotaUsedText

Retrieves the user's quota used value for the volume. This value is expressed as a text string, for example "10.5 MB". If the destination buffer is too small, the string is truncated to fit the buffer.

HRESULT GetQuotaUsedText(
  LPWSTR pszText,
  DWORD cchText
);

Parameters

pszText
Pointer to the buffer to receive the text string.
cchText
Size of the buffer, in bytes.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_INVALIDARG | The pszText parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetSid

Retrieves the user's security identifier (SID).

HRESULT GetSid(
  LPBYTE pbSidBuffer,
  DWORD cbSidBuffer
);

Parameters

pbSidBuffer
Pointer to the buffer to receive the SID.
cbSidBuffer
Size of the buffer, in bytes. Use the IDiskQuotaUser::GetSidLength method to obtain the required size for the buffer.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
E_INVALIDARG | The pbSidBuffer parameter is NULL.
ERROR_INVALID_SID | The SID for the user is invalid.
ERROR_INSUFFICIENT_BUFFER | Insufficient destination buffer size.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::GetSidLength

Retrieves the length of the user's security identifier (SID), in bytes. Use the return value to determine the size of the destination buffer you pass to IDiskQuotaUser::GetSid.

HRESULT GetSidLength(
  LPDWORD pdwLength
);

Parameters

pdwLength
Pointer to the variable to receive the SID length, in bytes.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
E_INVALIDARG | The pdwLength parameter is NULL.
ERROR_INVALID_SID | The SID for the user is invalid.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::Invalidate

Invalidates the quota information stored in the quota user object. The next time information is requested, it is refreshed from disk.

HRESULT Invalidate(void);

Parameters

This method has no parameters.

Return Values

This method returns NOERROR.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::SetQuotaLimit

Sets the user's quota limit value on the volume. The limit is set as the maximum amount of disk space available to the volume user.

HRESULT SetQuotaLimit(
  LONGLONG llLimit,
  BOOL fWriteThrough
);

Parameters

llLimit
Specifies the limit value, in bytes. If this value is -1, the user has an unlimited quota.
fWriteThrough
If this value is TRUE, the value is written immediately to the volume's quota file. Otherwise, the value is written only to the quota user object's local memory. This value should typically be set to TRUE. Set it to FALSE when using the IDiskQuotaUserBatch interface to modify multiple user quota entries at once.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_FAIL | An unexpected file system error occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUser::SetQuotaThreshold

Sets the user's warning threshold value on the volume. The threshold is an arbitrary value set by the volume's quota administrator. You can use it to identify users who are approaching their hard quota limit.

HRESULT SetQuotaThreshold(
  LONGLONG llThreshold,
  BOOL fWriteThrough
);

Parameters

llThreshold
Specifies the warning threshold value.
fWriteThrough
If this value is TRUE, the value is written immediately to the volume's quota file. Otherwise, the value is written only to the quota user object's local memory. This value should typically be set to TRUE. Set it to FALSE when using the IDiskQuotaUserBatch interface to modify multiple user quota entries at the same time.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
ERROR_LOCK_FAILED | Failure to obtain an exclusive lock.
E_FAIL | An unexpected file system error occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUser


IDiskQuotaUserBatch

The IDiskQuotaUserBatch interface enables you to add multiple quota user objects to a container that is then submitted for update in a single call. This reduces the number of calls to the underlying file system, improving update efficiency when a large number of user objects must be updated. This interface is instantiated by using the IDiskQuotaControl::CreateUserBatch method.

Virtual Function Table

IUnknown Methods

QueryInterface
AddRef
Release

IDiskQuotaUserBatch Methods

Add
Remove
RemoveAll
FlushToDisk

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces


IDiskQuotaUserBatch::Add

Adds an IDiskQuotaUser pointer to the batch list. This method calls AddRef on the pUser interface pointer. Release is automatically called on each contained IDiskQuotaUser interface pointer when the batch object is destroyed.

When setting values on a quota user object in preparation for batch processing, specify FALSE for the fWriteThrough parameter in the IDiskQuotaUser::SetQuotaLimit and IDiskQuotaUser::SetQuotaThreshold methods. This stores the values in memory without writing to disk. To write the changes to disk, call the IDiskQuotaUserBatch::FlushToDisk method.

HRESULT Add(
  PDISKQUOTA_USER pUser
);

Parameters

pUser
Pointer to the quota user object's IDiskQuotaUser interface.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
E_INVALIDARG | The pUser parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUserBatch


IDiskQuotaUserBatch::Remove

Removes an IDiskQuotaUser pointer from the batch list.

HRESULT Remove(
  PDISKQUOTA_USER pUser
);

Parameters

pUser
Pointer to the quota user object's IDiskQuotaUser interface.

Return Values

This method returns one of the following values.

Value | Meaning
S_OK | Success.
S_FALSE | Quota user object not found in batch.
E_INVALIDARG | The pUser parameter is NULL.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUserBatch


IDiskQuotaUserBatch::RemoveAll

Removes all IDiskQuotaUser pointers from the batch list.

HRESULT RemoveAll(void);

Parameters

This method has no parameters.

Return Values

This method returns one of the following values.

Value | Meaning
NOERROR | Success.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUserBatch


IDiskQuotaUserBatch::FlushToDisk

Writes user object changes to disk in a single call to the underlying file system.

HRESULT FlushToDisk(void);

Parameters

This method has no parameters.

Return Values

This method returns a file system error or one of the following values.

Value | Meaning
NOERROR | Success.
ERROR_ACCESS_DENIED | The caller has insufficient access rights.
E_OUTOFMEMORY | Insufficient memory.
E_FAIL | An unexpected file system error occurred.
E_UNEXPECTED | An unexpected exception occurred.

Remarks

There are limitations on the amount of information that can be written to disk in a single call to the file system. The flush operation may generate multiple calls to the file system. Nonetheless, the batch operation will be more efficient than a single call for each user object.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IDiskQuotaUserBatch


IEnumDiskQuotaUsers

The IEnumDiskQuotaUsers interface enumerates user quota entries on the volume. This interface is instantiated by using the IDiskQuotaControl::CreateEnumUsers method.

Virtual Function Table

IUnknown Methods

QueryInterface
AddRef
Release

IEnumDiskQuotaUsers Methods

Next
Skip
Reset
Clone

Remarks

To use this interface, the client directs an object that maintains a collection of items to create an enumerator object. By repeatedly calling the Next method, the client gets successive pointers to each item in the collection.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces


IEnumDiskQuotaUsers::Clone

Creates another enumerator that contains the same enumeration state as the current one. Using this method, a client can record a particular point in the enumeration sequence, and then return to that point at a later time. The new enumerator supports the same interface as the original one.

HRESULT Clone(
  IEnumDiskQuotaUsers **ppEnum
);

Parameters

ppEnum
Pointer to the variable to receive the IEnumDiskQuotaUsers interface pointer. If the method is unsuccessful, the value of this variable is undefined.

Return Values

This method returns one of the following values.

Value | Meaning
E_INVALIDARG | The ppEnum parameter is NULL.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | An unexpected exception occurred.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IEnumDiskQuotaUsers


IEnumDiskQuotaUsers::Next

Retrieves the next cUsers items in the enumeration sequence. If there are fewer than the requested number of elements left in the sequence, it retrieves the remaining elements. The number of elements actually retrieved is returned through pcUsersFetched (unless the caller passed in NULL for that parameter).

HRESULT Next(
  DWORD cUsers,
  PDISKQUOTA_USER *rgUsers,
  LPDWORD pcUsersFetched
);

Parameters

cUsers
Specifies the number of elements being requested.
rgUsers
Array of size cUsers or larger.
pcUsersFetched
Pointer to the number of elements actually supplied in rgUsers. The caller can pass in NULL if cUsers is one.

Return Values

The return value is NOERROR if the number of elements supplied is cUsers; otherwise, the return value is S_FALSE.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IEnumDiskQuotaUsers


IEnumDiskQuotaUsers::Reset

Resets the enumeration sequence to the beginning.

HRESULT Reset(void);

Parameters

This method has no parameters.

Return Values

The return value is NOERROR.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IEnumDiskQuotaUsers


IEnumDiskQuotaUsers::Skip

Skips over the next specified number of elements in the enumeration sequence.

HRESULT Skip(
  DWORD cUsers
);

Parameters

cUsers
Specifies the number of elements to be skipped.

Return Values

The return value is NOERROR if the number of elements skipped is cUsers; otherwise, the return value is S_FALSE.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Interfaces, IEnumDiskQuotaUsers


File System Structures

The following structures are used with file systems.

DISKQUOTA_USER_INFORMATION
EFS_CERTIFICATE_BLOB
EFS_HASH_BLOB
ENCRYPTION_CERTIFICATE
ENCRYPTION_CERTIFICATE_HASH
ENCRYPTION_CERTIFICATE_HASH_LIST
ENCRYPTION_CERTIFICATE_LIST


DISKQUOTA_USER_INFORMATION

The DISKQUOTA_USER_INFORMATION structure represents the per-user quota information.

typedef struct DiskQuotaUserInformation {
  LONGLONG QuotaUsed;
  LONGLONG QuotaThreshold;
  LONGLONG QuotaLimit;
} DISKQUOTA_USER_INFORMATION, *PDISKQUOTA_USER_INFORMATION;

Members

QuotaUsed
Disk space charged to the user, in bytes. This is the amount of information stored, not necessarily the number of bytes used on disk.
QuotaThreshold
Warning threshold for the user, in bytes. You can use the IDiskQuotaControl::SetQuotaLogFlags method to configure the system to generate a system logfile entry when the disk space charged to the user exceeds this value.
QuotaLimit
Quota limit for the user, in bytes. You can use the IDiskQuotaControl::SetQuotaLogFlags method to configure the system to generate a system logfile entry when the disk space charged to the user exceeds this value. You can also use the IDiskQuotaControl::SetQuotaState method to configure the system to deny additional disk space to the user when the disk space charged to the user exceeds this value.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Dskquota.h.

See Also

File Systems Overview, File System Structures, IDiskQuotaControl::SetQuotaLogFlags, IDiskQuotaControl::SetQuotaState, IDiskQuotaUser::GetQuotaInformation


EFS_CERTIFICATE_BLOB

The EFS_CERTIFICATE_BLOB structure contains a certificate.

typedef struct _CERTIFICATE_BLOB {
  DWORD dwCertEncodingType;
  DWORD cbData;
  PBYTE pbData;
} EFS_CERTIFICATE_BLOB, *PEFS_CERTIFICATE_BLOB;

Members

dwCertEncodingType
Specifies the certificate encoding type. This member can be one of the following values.

CRYPT_ASN_ENCODING
CRYPT_NDR_ENCODING
X509_ASN_ENCODING
X509_NDR_ENCODING

cbData
Specifies the number of bytes in the pbData buffer.
pbData
A binary certificate. The format of this certificate is specified by the dwCertEncodingType member.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, ENCRYPTION_CERTIFICATE


EFS_HASH_BLOB

The EFS_HASH_BLOB structure contains a certificate hash.

typedef struct _EFS_HASH_BLOB {
  DWORD cbData;
  PBYTE pbData;
} EFS_HASH_BLOB, *PEFS_HASH_BLOB;

Members

cbData
Specifies the number of bytes in the pbData buffer.
pbData
The certificate hash.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, ENCRYPTION_CERTIFICATE_HASH


ENCRYPTION_CERTIFICATE

The ENCRYPTION_CERTIFICATE structure contains a certificate.

typedef struct _ENCRYPTION_CERTIFICATE {
  DWORD cbTotalLength;
  SID *pUserSid;
  PEFS_CERTIFICATE_BLOB pCertBlob;
} ENCRYPTION_CERTIFICATE, *PENCRYPTION_CERTIFICATE;

Members

cbTotalLength
The length of this structure, in bytes.
pUserSid
The SID of the user who owns the certificate.
pCertBlob
Pointer to an EFS_CERTIFICATE_BLOB structure.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, EFS_CERTIFICATE_BLOB, ENCRYPTION_CERTIFICATE_LIST, SetUserFileEncryptionKey


ENCRYPTION_CERTIFICATE_HASH

The ENCRYPTION_CERTIFICATE_HASH structure contains a certificate hash.

typedef struct _ENCRYPTION_CERTIFICATE_HASH {
  DWORD cbTotalLength;
  SID *pUserSid;
  PEFS_HASH_BLOB pHash;
  LPWSTR lpDisplayInformation;
} ENCRYPTION_CERTIFICATE_HASH, *PENCRYPTION_CERTIFICATE_HASH;

Members

cbTotalLength
The length of this structure, in bytes.
pUserSid
The SID of the user who owns the certificate.
pHash
Pointer to an EFS_HASH_BLOB structure.
lpDisplayInformation

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, EFS_HASH_BLOB, ENCRYPTION_CERTIFICATE_HASH_LIST


ENCRYPTION_CERTIFICATE_HASH_LIST

The ENCRYPTION_CERTIFICATE_HASH_LIST structure is a list of certificate hashes.

typedef struct _ENCRYPTION_CERTIFICATE_HASH_LIST {
  DWORD nCert_Hash;
  PENCRYPTION_CERTIFICATE_HASH *pUsers;
} ENCRYPTION_CERTIFICATE_HASH_LIST, *PENCRYPTION_CERTIFICATE_HASH_LIST;

Members

nCert_Hash
Specifies the number of certificate hashes in the list.
pUsers
Pointer to the first ENCRYPTION_CERTIFICATE_HASH structure in the list.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, ENCRYPTION_CERTIFICATE_HASH, FreeEncryptionCertificateHashList, QueryRecoveryAgentsOnEncryptedFile, QueryUsersOnEncryptedFile, RemoveUsersFromEncryptedFile


ENCRYPTION_CERTIFICATE_LIST

The ENCRYPTION_CERTIFICATE_LIST structure is a list of certificates.

typedef struct _ENCRYPTION_CERTIFICATE_LIST {
  DWORD nUsers;
  PENCRYPTION_CERTIFICATE *pUsers;
} ENCRYPTION_CERTIFICATE_LIST, *PENCRYPTION_CERTIFICATE_LIST;

Members

nUsers
Specifies the number of certificates in the list.
pUsers
Pointer to the first ENCRYPTION_CERTIFICATE structure in the list.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winefs.h; include Windows.h.

See Also

File Systems Overview, File System Structures, AddUsersToEncryptedFile, ENCRYPTION_CERTIFICATE


File System Macros

The following macros are used with file systems.

IsReparseTagMicrosoft
IsReparseTagNameSurrogate


IsReparseTagMicrosoft

The IsReparseTagMicrosoft macro determines whether a reparse point tag indicates a Microsoft reparse point.

ULONG IsReparseTagMicrosoft(
  ULONG _tag  // tag to be tested
);

Parameters

_tag
Reparse point tag to be tested.

Return Values

The return value is a ULONG that must be treated as zero or nonzero. A nonzero return value indicates that the tag is a Microsoft tag. A zero return value indicates that the tag is not a Microsoft tag. Only software developed by Microsoft or in partnership with Microsoft can use Microsoft tags. All other software must use non-Microsoft tags.

Remarks

If the Microsoft tag bit is set, Microsoft provides the tag. All other tags must use zero for this bit.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.

See Also

File Systems Overview, File System Macros


IsReparseTagNameSurrogate

The IsReparseTagNameSurrogate macro determines whether a tag's associated reparse point is a surrogate for another named entity, for example a mount volume point.

ULONG IsReparseTagNameSurrogate(
  ULONG _tag  // tag to be tested
);

Parameters

_tag
Reparse point tag to be tested for surrogacy.

Return Values

The return value is a ULONG that must be treated as zero or nonzero. A nonzero return value means that the tag indicates a surrogate reparse point. A zero return value means that the tag does not indicate a surrogate reparse point.

Remarks

If the surrogacy bit is set, the file or directory represents another named entity in the system, such as a volume mounted at this directory. For more information on volume mounting, see Volume Mount Points and Mounting Volumes.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.

See Also

File Systems Overview, File System Macros


Tape Backup

The tape functions provided by the Microsoft® Win32® API enable backup applications to read from and write to a tape, initialize a tape, and retrieve tape or tape drive information.

  • About Tape Backup
  • Using Tape Backup
  • Tape Backup Reference


About Tape Backup

A tape volume consists of a recording medium and its physical carrier. The entire length of tape in a volume is not available for recording data. Short sections at the beginning and the end of the tape are reserved for attaching the tape to the hubs in the carrier. The first position on the tape where data can be recorded is the called the beginning-of-medium marker, and the last position is called the end-of-medium marker.

Every tape volume has one or more partitions. A partition is a portion of the volume, containing its own beginning and ending points, that does not overlap with any other portion of the volume. Each partition has three predefined positions. The first position in a partition where you can record data is called the beginning-of-partition marker, and the last is called end-of-partition marker. The early-warning position is located immediately before the end-of-partition marker. The early-warning position notifies tape applications to transfer buffered data to the tape before reaching the end-of-partition marker.

The area between a partition's beginning and ending points is typically divided into sections by filemarks or setmarks. Filemarks and setmarks are special recorded elements that do not contain user data; they simply divide the partition into smaller areas to provide an address scheme. Filemarks and setmarks serve similar purposes, but setmarks provide faster positioning on high-capacity tape drives.

Typically, tape devices support filemarks and setmarks. Support of both enables tape data to be formatted such that setmarks separate data from different disk volumes and filemarks separate data from individual files on a disk volume.

Another recorded element that denotes locations on the tape is an erase gap, an area of erased tape or a pattern that the device does not recognize as a mark or as user data.

There are three types of filemarks. A short filemark contains a short erase gap that cannot be overwritten unless the write operation is performed from the beginning of the partition or from an earlier long filemark. A long filemark contains a long erase gap that enables an application to position the tape at the beginning of the filemark and to overwrite the filemark and the erase gap. A normal filemark does not contain an erase gap. Tape devices that use filemarks support either short and long filemarks or normal filemarks, but not all three.

The area on a partition between setmarks or filemarks is available for recording data. A unit of data written to or read from a tape is referred to as a block.

  • Tape Initialization
  • Tape Input and Output


Tape Initialization

An application must use the CreateFile function to create a handle of a tape device. This handle is used in subsequent operations on the tape in the device.

Before an application writes to a tape, the tape must be formatted according to the needs of the application and the capabilities of the tape drive being used. The CreateTapePartition function reformats a tape, creating on it a given number of partitions of a specified size.

The PrepareTape function prepares a tape to be accessed or removed. This function can load, unload, lock, or unlock a tape. This function can also tension the tape by moving the tape to the end of the tape and back to the beginning.

To retrieve and set information about a tape and tape drive, an application uses the GetTapeParameters, SetTapeParameters, and GetTapeStatus functions.

GetTapeParameters retrieves information that describes a tape or a tape drive. The tape information includes the tape's type, density, and block size; the number of partitions on the tape; the amount of tape remaining; and so on. The tape drive information includes the drive's default block size, the maximum partition count, and the features that are supported.

SetTapeParameters either sets the tape block size or sets the tape drive flags that indicate whether the drive supports hardware error correction, data compression, data padding, or any combination of the three.

GetTapeStatus indicates whether the tape drive is ready to process tape commands.


Tape Input and Output

The Win32 API provides several functions that applications can use to perform input and output (I/O) on a tape drive. Tape I/O is similar to I/O performed on a communications device.

When performing tape I/O, some tape drives store tape firmware information in the first few blocks on a tape, typically using some portion of the first 100 blocks. Applications should not use those blocks. More specific information on this subject is available from individual tape system manufacturers. In general, an application that skips the first 100 blocks on a tape will avoid tape drive idiosyncrasies.

The GetTapePosition and SetTapePosition functions retrieve and move the current tape position. The WriteTapemark function writes a specified number of setmarks, filemarks, short filemarks, and long filemarks. The EraseTape function erases all or part of a tape.

The ReadFile and WriteFile functions read and write file data from and to the tape. The data is read and written in complete blocks. If the tape's block size is 512 bytes, all read and write operations must use buffers that are simple integer multiples of that block size: 512, 1024, 1536, 2048, and so on. Most, if not all, drives only allow a write operation after the tape is rewound or after a read operation produces an end-of-data error message.

If ReadFile encounters a filemark, the data up to the filemark is read and the function fails. (The GetLastError function returns an error code indicating the type of filemark that was encountered.) The operating system moves the tape past the filemark, and an application can call ReadFile again to continue reading.

ReadFile and WriteFile read and write only the data stream. The BackupRead and BackupWrite functions read and write all the streams associated with a file. These include data, extended attributes, security, and alternative data streams. The security and alternate data streams are relevant only on the NTFS partition.

The BackupSeek function seeks forward in a file initially accessed by BackupRead or BackupWrite. This function enables an application to skip information that causes access errors.

If an application needs to access only the file data, it should use ReadFile and WriteFile. These functions can also read alternative data streams if the streams were created by using the CreateFile function.

A tape-backup application must use BackupRead and BackupWrite to copy all information pertaining to a file. However, these functions do not read or write file characteristics such as attributes, file creation time, and so on. Applications must use the file input and output functions, such as GetFileAttributes and SetFileAttributes, to retrieve and set those values.


Using Tape Backup

  • Creating a backup application
  • Backing up and restoring POSIX file links


Creating a Backup Application

To perform any input or output on a tape, a backup application must first obtain a handle of the tape device. The following code sample shows how to use the CreateFile function to open a tape device.

HANDLE hTape;   // handle to tape device

hTape = CreateFile(
    "\\\\.\\TAPE0",               // name of tape device to open
    GENERIC_READ | GENERIC_WRITE, // read/write access
    0,                            // not used
    0,                            // not used
    OPEN_EXISTING,                // required for tape devices
    0,                            // not used
    NULL);                        // not used

To back up a directory tree to a tape, an application must use the FindFirstFile and FindNextFile functions to traverse the directory tree. Each time a file is found, the application should get the file's attributes by using the GetFileAttributes function. If there are hard links, the application should determine the number of links and save the file's unique identifier in a table for future comparisons. The first time a file is found, the application should use CreateFile to open the file and the BackupRead function to begin the backup. Then it can use the WriteFile function repeatedly to transfer all the information in the buffer used by BackupRead to the tape. The second time a file is found (checked against the table of file identifiers when there are hard links), the application can simply write the general file information to the tape, followed by a stream whose identifier is BACKUP_LINK.

When restoring files from tape to disk, an application must use the CreateFile, BackupWrite, and ReadFile functions. For each file on the tape, the application should use CreateFile to create a new file on disk and BackupWrite to begin restoring the file. Then it should use ReadFile repeatedly until all the information for the file has been read from the tape into the buffer filled by BackupWrite. If one of the streams in the BackupWrite buffer has a BACKUP_LINK stream identifier, the application must establish a hard link. If the data needed to establish the link does not exist, BackupWrite fails. The application can use a preexisting catalog to locate and restore the original data, or it can notify the user that the file data to be restored is in a different location.


Backing Up and Restoring POSIX File Links

A backup application can use the BackupWrite function to recreate POSIX file links.

The BackupRead function does not return POSIX file link data. A backup application must maintain the link information itself. The following pseudocode presents algorithms for backing up and restoring POSIX file link data along with other file information.

PseudoCode Algorithm for Backing Up POSIX File Links

1.  Initialize and empty a list of known links.
2.  While there are more files to back up
3.     Read the disk and get the next file.
4.     Open the file for read.
5.     Call GetFileInformationByHandle() to get the
          NumberOfLinks and the FileIndex.
6.     If the NumberOfLinks is greater than 1
7.        Search the list of known links looking for
             the same FileIndex.
8.           If a match is NOT found
9.              add the full path of the file and the
                   FileIndex to the list.
10.             Call BackupRead() to copy all data to
                   your backup media.
11.          Else
12.             Mark the data as a LINK on your backup media
13.             store the full path from the list
                   to your backup media.
14.          Endif
15.    Else
16.       Call BackupRead() to copy all data to your
             backup media.
17.    Endif
18. EndWhile

PseudoCode Algorithm for Restoring POSIX File Links

1.  While there are more files to restore
2.     If the file is a LINK
3.        use the full path which was saved as data
             to open the file.
4.        Initialize a WIN32_STREAM_ID structure with
             dwStreamId equal to BACKUP_LINK.
5.        Initialize the dwStreamAttributes to 0.
6.        Initialize the dwStreamNameSize to 0.
7.        Initialize a buffer containing the full path
             of the file you are restoring in UNICODE.
8.        Initialize the dwStreamSizeHigh to 0.
9.        Initialize the dwStreamSizeLow to the size
             in bytes of the buffer containing the full path.
10.       Compute the length of the variable-size WIN32_STREAM_ID
             buffer.
11.       Call BackupWrite() with the WIN32_STREAM_ID buffer.
12.       Call BackupWrite() with the buffer containing
             the full path.
13.          Else
14.       Call BackupWrite() with the data stored on
             your backup media.
15.    Endif
16.  EndWhile

For a C language implementation of the link restoration algorithm described above, refer to the following article in the Microsoft Knowledge Base:

ARTICLE ID: Q234727.


Tape Backup Reference

The following elements are used with tape backup.

  • Tape Backup Functions
  • Tape Backup Structures


Tape Backup Functions

The following functions are used with tape backup.

Function | Description
BackupRead | Reads data associated with a specified file or directory into a buffer.
BackupSeek | Seeks forward in a data stream.
BackupWrite | Writes a stream of data from a buffer to a specified file or directory.
CreateTapePartition | Reformats a tape.
EraseTape | Erases all or part of a tape.
GetTapeParameters | Retrieves information that describes the tape or the tape drive.
GetTapePosition | Retrieves the current address of the tape.
GetTapeStatus | Determines whether the tape device is ready to process tape commands.
PrepareTape | Prepares the tape to be accessed or removed.
SetTapeParameters | Specifies the block size of a tape or configures the tape device.
SetTapePosition | Sets the tape position on the specified device.
WriteTapemark | Writes a specified number of filemarks, setmarks, short filemarks, or long filemarks to a tape device.


BackupRead

The BackupRead function reads data associated with a specified file or directory into a buffer. You use this function to back up a file or directory.

BOOL BackupRead(
  HANDLE hFile,                // handle to file or directory
  LPBYTE lpBuffer,             // read buffer
  DWORD nNumberOfBytesToRead,  // number of bytes to read
  LPDWORD lpNumberOfBytesRead, // number of bytes read
  BOOL bAbort,                 // termination type
  BOOL bProcessSecurity,       // process security options
  LPVOID *lpContext            // context information
);

Parameters

hFile
[in] Handle to the file or directory being backed up. The function reads data associated with this file. You obtain this handle by calling the CreateFile function.

The BackupRead function fails if CreateFile was called with the flag FILE_FLAG_NO_BUFFERING. In this case, the GetLastError function returns the value ERROR_INVALID_PARAMETER.

lpBuffer
[out] Pointer to a buffer that the function writes data to.
nNumberOfBytesToRead
[in] Specifies the length of the buffer. The buffer size must be greater than the size of a WIN32_STREAM_ID structure.
lpNumberOfBytesRead
[out] Pointer to a variable that receives the number of bytes read.

If the function returns a nonzero value, and the variable pointed to by lpNumberOfBytesRead is zero, then all the data associated with the file handle has been read.

bAbort
[in] Indicates whether you have finished using BackupRead on the handle. While you are backing up the file, specify this parameter as FALSE. Once you are done using BackupRead, you must call BackupRead one more time specifying TRUE for this parameter and passing the appropriate lpContext. lpContext must be passed when bAbort is TRUE; all other parameters are ignored.
bProcessSecurity
[in] Indicates whether the function will restore the access-control list (ACL) data for the file or directory.

If bProcessSecurity is TRUE, the ACL data will be backed up.

lpContext
[out] Pointer to a variable that receives and holds a pointer to an internal data structure used by BackupRead to maintain context information during a backup operation.

You must set the variable pointed to by lpContext to NULL before the first call to BackupRead for the specified file or directory. The function allocates memory for the data structure, and then sets the variable to point to that structure. You must not change lpContext or the variable that it points to between calls to BackupRead.

To release the memory used by the data structure, call BackupRead with the bAbort parameter set to TRUE when the backup operation is complete.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information, call GetLastError.

Remarks

BackupRead processes all of the data pertaining to an opened object as a series of discrete byte streams. Each stream is preceded by a 32-bit aligned WIN32_STREAM_ID structure.

Streams must be processed in the same order in which they were written to the tape. This ordering enables applications to compare the data backed up against the data on the source device. The data returned by BackupRead is to be used only as input to the BackupWrite function. This data is returned as one large data stream divided into substreams. The substreams are separated by WIN32_STREAM_ID headers.

If an error occurs while BackupRead is reading, the calling process can skip the bad data by calling the BackupSeek function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, BackupWrite, BackupSeek, WIN32_STREAM_ID


BackupSeek

The BackupSeek function seeks forward in a data stream initially accessed by using the BackupRead or BackupWrite function.

BOOL BackupSeek(
  HANDLE hFile,               // handle to file
  DWORD dwLowBytesToSeek,     // low-order DWORD of number of bytes
  DWORD dwHighBytesToSeek,    // high-order DWORD of number of bytes
  LPDWORD lpdwLowByteSeeked,  // number of bytes to forward
  LPDWORD lpdwHighByteSeeked, // number of bytes forwarded
  LPVOID *lpContext           // context information
);

Parameters

hFile
[in] Handle to the file or directory being backed up. This handle is created by using the CreateFile function.
dwLowBytesToSeek
[in] Specifies the low-order bits of the number of bytes to seek.
dwHighBytesToSeek
[in] Specifies the high-order bits of the number of bytes to seek.
lpdwLowByteSeeked
[out] Pointer to a variable that receives the low-order bits of the number of bytes the function actually seeks.
lpdwHighByteSeeked
[out] Pointer to a variable that receives the high-order bits of the number of bytes the function actually seeks.
lpContext
[in] Pointer to an internal data structure used by the function. This structure must be the same structure that was initialized by the BackupRead function. An application must not touch the contents of this structure.

Return Values

If the function could seek the requested amount, the function returns a nonzero value.

If the function could not seek the requested amount, the function returns zero. To get extended error information, call GetLastError.

Remarks

Applications use the BackUpSeek function to skip portions of a data stream that cause errors. This function does not seek across stream headers. If an application attempts to seek past the end of a substream, the function fails, the lpdwLowByteSeeked and lpdwHighByteSeeked parameters indicate the actual number of bytes the function seeks, and the file position is placed at the start of the next stream header.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, BackupRead, BackupWrite, CreateFile


BackupWrite

The BackupWrite function writes a stream of data from a buffer to a specified file or directory. The data must be divided into substreams separated by WIN32_STREAM_ID structures. You use this function to restore a file or directory that has been backed up.

BOOL BackupWrite(
  HANDLE hFile,                   // handle to file or directory
  LPBYTE lpBuffer,                // write buffer
  DWORD nNumberOfBytesToWrite,    // number of bytes to write
  LPDWORD lpNumberOfBytesWritten, // number of bytes written
  BOOL bAbort,                    // termination type
  BOOL bProcessSecurity,          // process security
  LPVOID *lpContext               // context information
);

Parameters

hFile
[in] Handle to the file or directory being restored. The function writes data to this file. You obtain this handle by calling the CreateFile function.

The BackupWrite function fails if CreateFile was called with the flag FILE_FLAG_NO_BUFFERING. In this case, the GetLastError function returns the value ERROR_INVALID_PARAMETER.

lpBuffer
[in] Pointer to a buffer that the function writes data from.
nNumberOfBytesToWrite
[in] Specifies the length of the buffer. The buffer size must be greater than the size of a WIN32_STREAM_ID structure.
lpNumberOfBytesWritten
[out] Pointer to a variable that receives the number of bytes written.
bAbort
[in] Indicates whether you have finished using BackupWrite on the handle. While you are backing up the file, specify this parameter as FALSE. After you are done using BackupWrite, you must call BackupWrite one more time specifying TRUE for this parameter and passing the appropriate lpContext. lpContext must be passed when bAbort is TRUE; all other parameters are ignored.
bProcessSecurity
[in] Specifies whether the function will restore the access-control list (ACL) data for the file or directory.

If bProcessSecurity is TRUE, you need to have specified WRITE_OWNER and WRITE_DAC access when opening the file or directory handle. If the handle does not have those access rights, the operating system denies access to the ACL data, and ACL data restoration will not occur.

lpContext
[out] Pointer to a variable that receives a pointer to an internal data structure used by BackupWrite to maintain context information during a restore operation.

You must set the variable pointed to by lpContext to NULL before the first call to BackupWrite for the specified file or directory. The function allocates memory for the data structure, and then sets the variable to point to that structure. You must not change lpContext or the variable that it points to between calls to BackupWrite.

To release the memory used by the data structure, call BackupWrite with the bAbort parameter set to TRUE when the restore operation is complete.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero, indicating that an I/O error occurred. To get extended error information, call GetLastError.

Remarks

The BACKUP_LINK stream type lets you restore files with hard links.

Data obtained by the BackupRead function should only be used as input to the BackupWrite function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, BackupRead, BackupSeek, CreateFile, WIN32_STREAM_ID


CreateTapePartition

The CreateTapePartition function reformats a tape.

DWORD CreateTapePartition(
  HANDLE hDevice,           // handle to device
  DWORD dwPartitionMethod,  // new partition type
  DWORD dwCount,            // number of new partitions
  DWORD dwSize              // size of new partition
);

Parameters

hDevice
[in] Handle to the device where the new partition is to be created. This handle is created by using the CreateFile function.
dwPartitionMethod
[in] Specifies the type of partition to create. To determine what type of partitions your device supports, see the documentation for your hardware. This parameter can have one of the following values.
Value | Description
TAPE_FIXED_PARTITIONS | Partitions the tape based on the device's default definition of partitions. The dwCount and dwSize parameters are ignored.
TAPE_INITIATOR_PARTITIONS | Partitions the tape into the number and size of partitions specified by dwCount and dwSize, respectively, except for the last partition. The size of the last partition is the remainder of the tape.
TAPE_SELECT_PARTITIONS | Partitions the tape into the number of partitions specified by dwCount. The dwSize parameter is ignored. The size of the partitions is determined by the device's default partition size. For more specific information, refer to the documentation for your tape device.

dwCount
[in] Specifies the number of partitions to create. The GetTapeParameters function provides the maximum number of partitions a tape can support.
dwSize
[in] Specifies the size, in megabytes, of each partition. This value is ignored if the dwPartitionMethod parameter is TAPE_SELECT_PARTITIONS.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, it may return one of the following error codes:

Error | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

Creating partitions reformats the tape. All previous information recorded on the tape is destroyed.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, GetTapeParameters


EraseTape

The EraseTape function erases all or part of a tape.

DWORD EraseTape(
  HANDLE hDevice,     // handle to device
  DWORD dwEraseType,  // type of erasure to perform
  BOOL bImmediate     // return after erase operation begins
);

Parameters

hDevice
[in] Handle to the device where the tape is to be erased. This handle is created by using the CreateFile function.
dwEraseType
[in] Specifies the erasing technique. This parameter can be one of the following values.
Value | Description
TAPE_ERASE_LONG | Erases the tape from the current position to the end of the current partition.
TAPE_ERASE_SHORT | Writes an erase gap or end-of-data marker at the current position.

bImmediate
[in] Specifies whether to return as soon as the erase operation begins. If this parameter is TRUE, the function returns immediately; if it is FALSE, the function does not return until the erase operation has been completed.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

Some tape devices do not support certain tape operations. To determine your tape device's capabilities, see your tape device documentation and use the GetTapeParameters function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, GetTapeParameters


GetTapeParameters

The GetTapeParameters function retrieves information that describes the tape or the tape drive.

DWORD GetTapeParameters(
  HANDLE hDevice,           // handle to device
  DWORD dwOperation,        // information type
  LPDWORD lpdwSize,         // information
  LPVOID lpTapeInformation  // tape media or drive information
);

Parameters

hDevice
[in] Handle to the device about which information is sought. This handle is created by using the CreateFile function.
dwOperation
[in] Specifies the type of information requested. This parameter must be one of the following values.
Value | Description
GET_TAPE_MEDIA_INFORMATION | Retrieves information about the tape in the tape device.
GET_TAPE_DRIVE_INFORMATION | Retrieves information about the tape device.

lpdwSize
[out] Pointer to a variable that receives the size, in bytes, of the buffer specified by the lpTapeInformation parameter. If the buffer is too small, this parameter receives the required size.
lpTapeInformation
[out] Pointer to a structure that contains the requested information. If the dwOperation parameter is GET_TAPE_MEDIA_INFORMATION, lpTapeInformation points to a TAPE_GET_MEDIA_PARAMETERS structure.

If dwOperation is GET_TAPE_DRIVE_INFORMATION, lpTapeInformation points to a TAPE_GET_DRIVE_PARAMETERS structure.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

The block size range values (maximum and minimum) returned by the GetTapeParameters function called with the dwOperation parameter set to the GET_TAPE_DRIVE_INFORMATION value will indicate system limits, not drive limits. However, it is the tape drive device and the media present in the drive that determine the true block size limits. Thus, an application may not be able to set all the block sizes mentioned in the range obtained by specifying GET_TAPE_DRIVE_INFORMATION in dwOperation.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, SetTapeParameters, TAPE_GET_DRIVE_PARAMETERS, TAPE_GET_MEDIA_PARAMETERS


GetTapePosition

The GetTapePosition function retrieves the current address of the tape, in logical or absolute blocks.

DWORD GetTapePosition(
  HANDLE hDevice,          // handle to device
  DWORD dwPositionType,    // address type
  LPDWORD lpdwPartition,   // current tape partition
  LPDWORD lpdwOffsetLow,   // low-order bits of position
  LPDWORD lpdwOffsetHigh   // high-order bits of position
);

Parameters

hDevice
[in] Handle to the device on which to get the tape position. This handle is created by using CreateFile.
dwPositionType
[in] Specifies the type of address to obtain. This parameter can be one of the following values.
Value | Description
TAPE_ABSOLUTE_POSITION | The lpdwOffsetLow and lpdwOffsetHigh parameters receive the device-specific block address. The dwPartition parameter receives zero.
TAPE_LOGICAL_POSITION | The lpdwOffsetLow and lpdwOffsetHigh parameters receive the logical block address. The dwPartition parameter receives the logical tape partition.

lpdwPartition
[out] Pointer to a variable that receives the number of the current tape partition. Partitions are numbered logically from 1 through n, where 1 is the first partition on the tape and n is the last. When a device-specific block address is retrieved, or if the device supports only one partition, this parameter receives zero.
lpdwOffsetLow
[out] Pointer to a variable that receives the low-order bits of the current tape position.
lpdwOffsetHigh
[out] Pointer to a variable that receives the high-order bits of the current tape position. This parameter can be NULL if the high-order bits are not required.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

A logical block address is relative to a partition. The first logical block address on each partition is zero.

Call the GetTapeParameters function to obtain information about the status, capabilities, and capacities of tape drives and media.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, GetTapeParameters, SetTapePosition


GetTapeStatus

The GetTapeStatus function determines whether the tape device is ready to process tape commands.

DWORD GetTapeStatus(
  HANDLE hDevice   // handle to device
);

Parameters

hDevice
[in] Handle to the device for which to get the device status. This handle is created by using the CreateFile function.

Return Values

If the tape device is ready to accept appropriate tape-access commands without returning errors, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error code | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_DEVICE_REQUIRES_CLEANING | The tape drive is capable of reporting that it requires cleaning, and reports that it does require cleaning.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile


PrepareTape

The PrepareTape function prepares the tape to be accessed or removed.

DWORD PrepareTape(
  HANDLE hDevice,     // handle to device
  DWORD dwOperation,  // preparation method
  BOOL bImmediate     // return after operation begins
);

Parameters

hDevice
[in] Handle to the device preparing the tape. This handle is created by using the CreateFile function.
dwOperation
[in] Specifies how the tape device is to be prepared. This parameter can be one of the following values.
Value | Meaning
TAPE_FORMAT | Performs a low-level format of the tape. Currently, only the QIC117 device supports this feature.
TAPE_LOAD | Loads the tape and moves the tape to the beginning.
TAPE_LOCK | Locks the tape ejection mechanism so that the tape is not ejected accidentally.
TAPE_TENSION | Adjusts the tension by moving the tape to the end of the tape and back to the beginning. This option is not supported by all devices. This value is ignored if it is not supported.
TAPE_UNLOAD | Moves the tape to the beginning for removal from the device. After a successful unload operation, the device returns errors to applications that attempt to access the tape, until the tape is loaded again.
TAPE_UNLOCK | Unlocks the tape ejection mechanism.

bImmediate
[in] Specifies whether to return as soon as the preparation begins. If this parameter is TRUE, the function returns immediately. If it is FALSE, the function does not return until the operation has been completed.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

Some tape devices do not support certain tape operations. See your tape device documentation and use the GetTapeParameters function to determine your tape device's capabilities.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, GetTapeParameters


SetTapeParameters

The SetTapeParameters function either specifies the block size of a tape or configures the tape device.

DWORD SetTapeParameters(
  HANDLE hDevice,           // handle to device
  DWORD dwOperation,        // information type
  LPVOID lpTapeInformation  // information buffer
);

Parameters

hDevice
[in] Handle to the device for which to set configuration information. This handle is created by using the CreateFile function.
dwOperation
[in] Specifies the type of information to set. This parameter must be one of the following values.
Value | Description
SET_TAPE_MEDIA_INFORMATION | Sets the tape-specific information specified by the lpTapeInformation parameter.
SET_TAPE_DRIVE_INFORMATION | Sets the device-specific information specified by lpTapeInformation.

lpTapeInformation
[in] Pointer to a structure that contains the information to set. If the dwOperation parameter is SET_TAPE_MEDIA_INFORMATION, lpTapeInformation points to a TAPE_SET_MEDIA_PARAMETERS structure.

If dwOperation is SET_TAPE_DRIVE_INFORMATION, lpTapeInformation points to a TAPE_SET_DRIVE_PARAMETERS structure.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, GetTapeParameters, TAPE_SET_DRIVE_PARAMETERS, TAPE_SET_MEDIA_PARAMETERS


SetTapePosition

The SetTapePosition sets the tape position on the specified device.

DWORD SetTapePosition(
  HANDLE hDevice,          // handle to device
  DWORD dwPositionMethod,  // positioning type
  DWORD dwPartition,       // new tape partition
  DWORD dwOffsetLow,       // low-order bits of position
  DWORD dwOffsetHigh,      // high-order bits of position
  BOOL bImmediate          // return after operation begins
);

Parameters

hDevice
[in] Handle to the device on which to set the tape position. This handle is created by using the CreateFile function.
dwPositionMethod
[in] Specifies the type of positioning to perform. This parameter must be one of the following values.
Value | Meaning
TAPE_ABSOLUTE_BLOCK | Moves the tape to the device-specific block address specified by the dwOffsetLow and dwOffsetHigh parameters. The dwPartition parameter is ignored.
TAPE_LOGICAL_BLOCK | Moves the tape to the block address specified by dwOffsetLow and dwOffsetHigh in the partition specified by dwPartition.
TAPE_REWIND | Moves the tape to the beginning of the current partition. The dwPartition, dwOffsetLow, and dwOffsetHigh parameters are ignored.
TAPE_SPACE_END_OF_DATA | Moves the tape to the end of the data on the partition specified by dwPartition.
TAPE_SPACE_FILEMARKS | Moves the tape forward (or backward) the number of filemarks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.
TAPE_SPACE_RELATIVE_BLOCKS | Moves the tape forward (or backward) the number of blocks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_FMKS | Moves the tape forward (or backward) to the first occurrence of n filemarks in the current partition, where n is the number specified by dwOffsetLow and dwOffsetHigh. The dwPartition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_SMKS | Moves the tape forward (or backward) to the first occurrence of n setmarks in the current partition, where n is the number specified by dwOffsetLow and dwOffsetHigh. The dwPartition parameter is ignored.
TAPE_SPACE_SETMARKS | Moves the tape forward (or backward) the number of setmarks specified by dwOffsetLow and dwOffsetHigh in the current partition. The dwPartition parameter is ignored.

dwPartition
[in] Specifies the partition to position within. If dwPartition is zero, the current partition is used. Partitions are numbered logically from 1 through n, where 1 is the first partition on the tape and n is the last.
dwOffsetLow
[in] Specifies the low-order bits of the block address or count for the position operation specified by the dwPositionMethod parameter.
dwOffsetHigh
[in] Specifies the high-order bits of the block address or count for the position operation specified by the dwPositionMethod parameter. If the high-order bits are not required, this parameter should be zero.
bImmediate
[in] Indicates whether to return as soon as the move operation begins. If this parameter is TRUE, the function returns immediately; if FALSE, the function does not return until the move operation has been completed.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

If the offset specified by dwOffsetLow and dwOffsetHigh specifies the number of blocks, filemarks, or setmarks to move, a positive offset moves the tape forward to the end of the last block, filemark, or setmark. A negative offset moves the tape backward to the beginning of the last block, filemark, or setmark. If the offset is zero, the tape does not move.

To obtain information about the status, capabilities, and capacities of tape drives and media, call the GetTapeParameters function.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile, GetTapeParameters, GetTapePosition


WriteTapemark

The WriteTapemark function writes a specified number of filemarks, setmarks, short filemarks, or long filemarks to a tape device. These tapemarks divide a tape partition into smaller areas.

DWORD WriteTapemark(
  HANDLE hDevice,        // handle to device
  DWORD dwTapemarkType,  // tapemark type
  DWORD dwTapemarkCount, // number of tapemarks to write
  BOOL bImmediate        // return after write begins
);

Parameters

hDevice
[in] Handle to the device on which to write tapemarks. This handle is created by using the CreateFile function.
dwTapemarkType
[in] Specifies the type of tapemarks to write. This parameter can be one of the following values.
Value | Description
TAPE_FILEMARKS | Writes the number of filemarks specified by the dwTapemarkCount parameter.
TAPE_LONG_FILEMARKS | Writes the number of long filemarks specified by dwTapemarkCount.
TAPE_SETMARKS | Writes the number of setmarks specified by dwTapemarkCount.
TAPE_SHORT_FILEMARKS | Writes the number of short filemarks specified by dwTapemarkCount.

dwTapemarkCount
[in] Specifies the number of tapemarks to write.
bImmediate
[in] Specifies whether to return as soon as the operation begins. If this parameter is TRUE, the function returns immediately; if it is FALSE, the function does not return until the operation has been completed.

Return Values

If the function succeeds, the return value is NO_ERROR.

If the function fails, the return value is one of the following error codes:

Error | Description
ERROR_BEGINNING_OF_MEDIA | An attempt to access data before the beginning-of-medium marker failed.
ERROR_BUS_RESET | A reset condition was detected on the bus.
ERROR_END_OF_MEDIA | The end-of-tape marker was reached during an operation.
ERROR_FILEMARK_DETECTED | A filemark was reached during an operation.
ERROR_SETMARK_DETECTED | A setmark was reached during an operation.
ERROR_NO_DATA_DETECTED | The end-of-data marker was reached during an operation.
ERROR_PARTITION_FAILURE | The tape could not be partitioned.
ERROR_INVALID_BLOCK_LENGTH | The block size is incorrect on a new tape in a multivolume partition.
ERROR_DEVICE_NOT_PARTITIONED | The partition information could not be found when a tape was being loaded.
ERROR_MEDIA_CHANGED | The tape that was in the drive has been replaced or removed.
ERROR_NO_MEDIA_IN_DRIVE | There is no media in the drive.
ERROR_NOT_SUPPORTED | The tape driver does not support a requested function.
ERROR_UNABLE_TO_LOCK_MEDIA | An attempt to lock the ejection mechanism failed.
ERROR_UNABLE_TO_UNLOAD_MEDIA | An attempt to unload the tape failed.
ERROR_WRITE_PROTECT | The media is write protected.

Remarks

Filemarks, setmarks, short filemarks, and long filemarks are special recorded elements that denote the linear organization of the tape. None of these marks contain user data. Filemarks are the most general marks; setmarks provide a hierarchy not available with filemarks.

A short filemark contains a short erase gap that cannot be overwritten unless the write operation is performed from the beginning of the partition or from an earlier long filemark.

A long filemark contains a long erase gap that allows an application to position the tape at the beginning of the filemark and to overwrite the filemark and the erase gap.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Tape Backup Overview, Tape Backup Functions, CreateFile


Tape Backup Structures

The following structures are used with tape backup.

TAPE_ERASE
TAPE_GET_DRIVE_PARAMETERS
TAPE_GET_MEDIA_PARAMETERS
TAPE_GET_POSITION
TAPE_PREPARE
TAPE_SET_DRIVE_PARAMETERS
TAPE_SET_MEDIA_PARAMETERS
TAPE_SET_POSITION
TAPE_WRITE_MARKS
WIN32_STREAM_ID


TAPE_ERASE

The TAPE_ERASE structure describes the partition to be erased.

typedef struct _TAPE_ERASE {
  DWORD Type;
  BOOLEAN Immediate;
} TAPE_ERASE, *PTAPE_ERASE;

Members

Type
Specifies how to erase the tape. This member must have one of the following values:
Value | Description
TAPE_ERASE_LONG | Erases the entire partition.
TAPE_ERASE_SHORT | Erases only the partition's header block.

Immediate
Specifies whether to return as soon as the erase operation begins.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_GET_DRIVE_PARAMETERS

The TAPE_GET_DRIVE_PARAMETERS structure describes the tape drive.

typedef struct _TAPE_GET_DRIVE_PARAMETERS {
  BOOLEAN ECC;
  BOOLEAN Compression;
  BOOLEAN DataPadding;
  BOOLEAN ReportSetmarks;
  DWORD   DefaultBlockSize;
  DWORD   MaximumBlockSize;
  DWORD   MinimumBlockSize;
  DWORD   MaximumPartitionCount;
  DWORD   FeaturesLow;
  DWORD   FeaturesHigh;
  DWORD   EOTWarningZoneSize;
} TAPE_GET_DRIVE_PARAMETERS, *PTAPE_GET_DRIVE_PARAMETERS;

Members

ECC
Specifies whether the device supports hardware error correction. This member is TRUE if hardware error correction is supported.
Compression
Specifies whether hardware data compression is enabled or disabled. This member is TRUE if hardware data compression is enabled.
DataPadding
Specifies whether data padding is enabled or disabled. Data padding keeps the tape streaming at a constant speed. This member is TRUE if data padding is enabled.
ReportSetmarks
Specifies whether setmark reporting is enabled or disabled. This member is TRUE if setmark reporting is enabled.
DefaultBlockSize
Specifies the device's default fixed block size.
MaximumBlockSize
Specifies the device's maximum block size.
MinimumBlockSize
Specifies the device's minimum block size.
MaximumPartitionCount
Specifies the maximum number of partitions that can be created on the device.
FeaturesLow
Specifies the low-order bits of the device features flag. This member can be one or more of following values.
Value | Meaning
TAPE_DRIVE_COMPRESSION | The device supports hardware data compression.
TAPE_DRIVE_CLEAN_REQUESTS | The device can report if cleaning is required.
TAPE_DRIVE_ECC | The device supports hardware error correction.
TAPE_DRIVE_EJECT_MEDIA | The device physically ejects the tape on a software eject.
TAPE_DRIVE_ERASE_BOP_ONLY | The device performs the erase operation from the beginning-of-partition marker only.
TAPE_DRIVE_ERASE_LONG | The device performs a long erase operation.
TAPE_DRIVE_ERASE_IMMEDIATE | The device performs an immediate erase operation — that is, it returns when the erase operation begins.
TAPE_DRIVE_ERASE_SHORT | The device performs a short erase operation.
TAPE_DRIVE_FIXED | The device creates fixed data partitions.
TAPE_DRIVE_FIXED_BLOCK | The device supports fixed-length block mode.
TAPE_DRIVE_INITIATOR | The device creates initiator-defined partitions.
TAPE_DRIVE_PADDING | The device supports data padding.
TAPE_DRIVE_GET_ABSOLUTE_BLK | The device provides the current device-specific block address.
TAPE_DRIVE_GET_LOGICAL_BLK | The device provides the current logical block address (and logical tape partition).
TAPE_DRIVE_REPORT_SMKS | The device supports setmark reporting.
TAPE_DRIVE_SELECT | The device creates select data partitions.
TAPE_DRIVE_SET_EOT_WZ_SIZE | The device supports setting the end-of-medium warning size.
TAPE_DRIVE_SET_CMP_BOP_ONLY | The device must be at the beginning of a partition before it can set compression on.
TAPE_DRIVE_TAPE_CAPACITY | The device returns the maximum capacity of the tape.
TAPE_DRIVE_TAPE_REMAINING | The device returns the remaining capacity of the tape.
TAPE_DRIVE_VARIABLE_BLOCK | The device supports variable-length block mode.
TAPE_DRIVE_WRITE_PROTECT | The device returns an error if the tape is write-enabled or write-protected.

FeaturesHigh
Contains the high-order bits of the device features flag. This member can be one or more of the following values.
Value | Meaning
TAPE_DRIVE_ABS_BLK_IMMED | The device moves the tape to a device-specific block address and returns as soon as the move begins.
TAPE_DRIVE_ABSOLUTE_BLK | The device moves the tape to a device specific block address.
TAPE_DRIVE_END_OF_DATA | The device moves the tape to the end-of-data marker in a partition.
TAPE_DRIVE_FILEMARKS | The device moves the tape forward (or backward) a specified number of filemarks.
TAPE_DRIVE_LOAD_UNLOAD | The device enables and disables the device for further operations.
TAPE_DRIVE_LOAD_UNLD_IMMED | The device supports immediate load and unload operations.
TAPE_DRIVE_LOCK_UNLOCK | The device enables and disables the tape ejection mechanism.
TAPE_DRIVE_LOCK_UNLK_IMMED | The device supports immediate lock and unlock operations.
TAPE_DRIVE_LOG_BLK_IMMED | The device moves the tape to a logical block address in a partition and returns as soon as the move begins.
TAPE_DRIVE_LOGICAL_BLK | The device moves the tape to a logical block address in a partition.
TAPE_DRIVE_RELATIVE_BLKS | The device moves the tape forward (or backward) a specified number of blocks.
TAPE_DRIVE_REVERSE_POSITION | The device moves the tape backward over blocks, filemarks, or setmarks.
TAPE_DRIVE_REWIND_IMMEDIATE | The device supports immediate rewind operation.
TAPE_DRIVE_SEQUENTIAL_FMKS | The device moves the tape forward (or backward) to the first occurrence of a specified number of consecutive filemarks.
TAPE_DRIVE_SEQUENTIAL_SMKS | The device moves the tape forward (or backward) to the first occurrence of a specified number of consecutive setmarks.
TAPE_DRIVE_SET_BLOCK_SIZE | The device supports setting the size of a fixed-length logical block or setting the variable-length block mode.
TAPE_DRIVE_SET_COMPRESSION | The device enables and disables hardware data compression.
TAPE_DRIVE_SET_ECC | The device enables and disables hardware error correction.
TAPE_DRIVE_SET_PADDING | The device enables and disables data padding.
TAPE_DRIVE_SET_REPORT_SMKS | The device enables and disables the reporting of setmarks.
TAPE_DRIVE_SETMARKS | The device moves the tape forward (or reverse) a specified number of setmarks.
TAPE_DRIVE_SPACE_IMMEDIATE | The device supports immediate spacing.
TAPE_DRIVE_TENSION | The device supports tape tensioning.
TAPE_DRIVE_TENSION_IMMED | The device supports immediate tape tensioning.
TAPE_DRIVE_WRITE_FILEMARKS | The device writes filemarks.
TAPE_DRIVE_WRITE_LONG_FMKS | The device writes long filemarks.
TAPE_DRIVE_WRITE_MARK_IMMED | The device supports immediate writing of short and long filemarks.
TAPE_DRIVE_WRITE_SETMARKS | The device writes setmarks.
TAPE_DRIVE_WRITE_SHORT_FMKS | The device writes short filemarks.

EOTWarningZoneSize
Indicates the number of bytes between the end-of-tape warning and the physical end of the tape.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_GET_MEDIA_PARAMETERS

The TAPE_GET_MEDIA_PARAMETERS structure describes the tape in the tape drive.

typedef struct _TAPE_GET_MEDIA_PARAMETERS {
  LARGE_INTEGER   Capacity;
  LARGE_INTEGER   Remaining;
  DWORD   BlockSize;
  DWORD   PartitionCount;
  BOOLEAN WriteProtected;
} TAPE_GET_MEDIA_PARAMETERS, *PTAPE_GET_MEDIA_PARAMETERS;

Members

Capacity
Specifies the total number of bytes on the current tape partition.
Remaining
Specifies the number of bytes between the current position and the end of the current tape partition.
BlockSize
Specifies the number of bytes per block.
PartitionCount
Specifies the number of partitions on the tape.
WriteProtected
Specifies whether the tape is write-protected. If this member is TRUE, the tape is write-protected.

Remarks

The GetTapeParameters function fills the Remaining and Capacity members with estimates of the tape remaining in the current tape partition and the total capacity of the current tape partition.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures, GetTapeParameters


TAPE_GET_POSITION

The TAPE_GET_POSITION structure describes the position of the tape.

typedef struct _TAPE_GET_POSITION {
  DWORD Type;
  DWORD Partition;
  LARGE_INTEGER Offset;
} TAPE_GET_POSITION, *PTAPE_GET_POSITION;

Members

Type
Specifies the type of position. This member must be one of the following values.
Value | Description
TAPE_ABSOLUTE_POSITION | The position specified by the Offset member is an absolute number of blocks from the beginning of the partition specified by the Partition member.
TAPE_LOGICAL_POSITION | The position specified by the Offset member is relative to the current position in the partition specified by Partition.

Partition
Specifies the partition to position within. If this member is zero, the current partition is assumed.
Offset
Specifies the block address.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_PREPARE

The TAPE_PREPARE structure describes how to prepare the tape.

typedef struct _TAPE_PREPARE {
  DWORD Operation;
} TAPE_PREPARE, *PTAPE_PREPARE;

Members

Operation
Specifies how to prepare the tape. This member must be one of the following values.
Value | Description
TAPE_LOCK | Locks the tape ejection mechanism so that the tape is not ejected accidentally during a tape operation.
TAPE_TENSION | Moves to the end of the tape and rewinds to the beginning of the tape. This value is ignored if the tape device does not support tensioning.
TAPE_UNLOAD | Rewinds and unloads the tape.
TAPE_UNLOCK | Unlocks the tape ejection mechanism.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_SET_DRIVE_PARAMETERS

The TAPE_SET_DRIVE_PARAMETERS structure describes the tape drive.

typedef struct _TAPE_SET_DRIVE_PARAMETERS {
  BOOLEAN ECC;
  BOOLEAN Compression;
  BOOLEAN DataPadding;
  BOOLEAN ReportSetmarks;
  DWORD   EOTWarningZoneSize;
} TAPE_SET_DRIVE_PARAMETERS, *PTAPE_SET_DRIVE_PARAMETERS;

Members

ECC
Specifies whether the device supports hardware error correction. This member is TRUE if hardware error correction is supported.
Compression
Specifies whether hardware data compression is enabled or disabled. This member is TRUE if hardware data compression is enabled.
DataPadding
Specifies whether data padding is enabled or disabled. Data padding keeps the tape streaming at a constant speed. This member is TRUE if data padding is enabled.
ReportSetmarks
Specifies whether setmark reporting is enabled or disabled. This member is TRUE if setmarks are enabled.
EOTWarningZoneSize
Specifies the number of bytes between the end-of-tape warning and the physical end of the tape.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_SET_MEDIA_PARAMETERS

The TAPE_SET_MEDIA_PARAMETERS structure describes the tape in the tape drive.

typedef struct _TAPE_SET_MEDIA_PARAMETERS {
  DWORD BlockSize;
} TAPE_SET_MEDIA_PARAMETERS, *PTAPE_SET_MEDIA_PARAMETERS;

Members

BlockSize
Specifies the number of bytes per block. Maximum and minimum block sizes can be obtained by calling the GetTapeParameters function.

Remarks

There is no longer a requirement that block sizes be powers of 2.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures, GetTapeParameters, SetTapeParameters


TAPE_SET_POSITION

The TAPE_SET_POSITION structure describes how and where to position the tape.

typedef struct _TAPE_SET_POSITION {
  DWORD Method;
  DWORD Partition;
  LARGE_INTEGER Offset;
  BOOLEAN Immediate;
} TAPE_SET_POSITION, *PTAPE_SET_POSITION;

Members

Method
Specifies the type of positioning. This member must be one of the following values.
Value | Description
TAPE_ABSOLUTE_BLOCK | Moves the tape to the device-specific block address specified by the Offset member. The Partition member is ignored.
TAPE_LOGICAL_BLOCK | Moves the tape to the block address specified by Offset in the partition specified by Partition.
TAPE_REWIND | Moves the tape to the beginning of the current partition. The Partition and Offset members are ignored.
TAPE_SPACE_END_OF_DATA | Moves the tape to the end of the data on the partition specified by Partition.
TAPE_SPACE_FILEMARKS | Moves the tape forward (or backward) the number of filemarks specified by Offset in the current partition. The Partition member is ignored.
TAPE_SPACE_RELATIVE_BLOCKS | Moves the tape forward (or backward) the number of blocks specified by Offset in the current partition. The Partition member is ignored.
TAPE_SPACE_SEQUENTIAL_FMKS | Moves the tape forward (or backward) to the first occurrence of n filemarks in the current partition, where n is the number specified by Offset. The Partition parameter is ignored.
TAPE_SPACE_SEQUENTIAL_SMKS | Moves the tape forward (or backward) to the first occurrence of n setmarks in the current partition, where n is the number specified by Offset. The Partition member is ignored.
TAPE_SPACE_SETMARKS | Moves the tape forward (or backward) the number of setmarks specified by Offset in the current partition. The Partition member is ignored.

Partition
Specifies the partition to position within. If this member is zero, the current partition is assumed.
Offset
Specifies the block address or count for the position operation specified by the Method member.
Immediate
Specifies whether to return as soon as the operation begins.

Remarks

If the positioning is relative, a positive offset moves the tape forward (toward the end of the tape) and a negative offset moves the tape backward (toward the beginning of the tape).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


TAPE_WRITE_MARKS

The TAPE_WRITE_MARKS structure describes the type and number of tapemarks to write.

typedef struct _TAPE_WRITE_MARKS {
  DWORD Type;
  DWORD Count;
  BOOLEAN Immediate;
} TAPE_WRITE_MARKS, *PTAPE_WRITE_MARKS;

Members

Type
Specifies the type of tapemark to write. This member can be one of the following values.
Value | Description
TAPE_LONG_FILEMARKS | Writes long filemarks.
TAPE_SEQUENTIAL_FILEMARKS | Writes sequential filemarks.
TAPE_SETMARKS | Writes setmarks.
TAPE_SHORT_FILEMARKS | Writes short filemarks.

Count
Specifies the number of tapemarks to write.
Immediate
Specifies whether to return as soon as the operation begins.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winnt.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures


WIN32_STREAM_ID

The WIN32_STREAM_ID structure contains stream data.

typedef struct _WIN32_STREAM_ID {
  DWORD         dwStreamId;
  DWORD         dwStreamAttributes;
  LARGE_INTEGER Size;
  DWORD         dwStreamNameSize;
  WCHAR         cStreamName[ANYSIZE_ARRAY];
} WIN32_STREAM_ID, *LPWIN32_STREAM_ID;

Members

dwStreamId
Specifies the type of data. This member can be one of the following values.
Value | Meaning
BACKUP_DATA | Standard data
BACKUP_EA_DATA | Extended attribute data
BACKUP_SECURITY_DATA | Security descriptor data
BACKUP_ALTERNATE_DATA | Alternative data streams
BACKUP_LINK | Hard link information
BACKUP_PROPERTY_DATA | Property data
BACKUP_OBJECT_ID | Objects identifiers
BACKUP_REPARSE_DATA | Reparse points
BACKUP_SPARSE_BLOCK | Sparse file.

dwStreamAttributes
Specifies the attributes of data to facilitate cross-operating system transfer. This member can be one or more of the following values.
Value | Description
STREAM_MODIFIED_WHEN_READ | Attribute set if the stream contains data that is modified when read. Allows the backup application to know that verification of data will fail.
STREAM_CONTAINS_SECURITY | Stream contains security data (general attributes). Allows the stream to be ignored on cross-operations restore.

Size
Specifies the size, in bytes, of data.
dwStreamNameSize
Specifies the length of the name of the alternative data stream.
cStreamName
Specifies the name of the alternative data stream, in Unicode.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Tape Backup Overview, Tape Backup Structures, BackupRead, BackupSeek, BackupWrite


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.