Performing Synchronous Device IO

[Previous] [Next]

This section discusses the Windows functions that allow you to perform synchronous device I/O. Keep in mind that a device can be a file, mailslot, pipe, socket, and so on. No matter which device is used, the I/O is performed using the same functions.

Without a doubt, the easiest and most commonly used functions for reading from and writing to devices are ReadFile and WriteFile:

BOOL ReadFile(    HANDLE      hfile,     PVOID       pvBuffer,    DWORD       nNumBytesToRead,     PDWORD      pdwNumBytes,    OVERLAPPED* pOverlapped); BOOL WriteFile(    HANDLE      hfile,     CONST VOID  *pvBuffer,    DWORD       nNumBytesToWrite,     PDWORD      pdwNumBytes,    OVERLAPPED* pOverlapped); 

The hfile parameter identifies the handle of the device you want to access. When the device is opened, you must not specify the FILE_FLAG_ OVERLAPPED flag, or the system will think that you want to perform asynchronous I/O with the device. The pvBuffer parameter points to the buffer to which the device's data should be read or to the buffer containing the data that should be written to the device. The nNumBytesToRead and nNumBytesToWrite parameters tell ReadFile and WriteFile how many bytes to read from the device and how many bytes to write to the device, respectively.

The pdwNumBytes parameters indicate the address of a DWORD that the functions fill with the number of bytes successfully transmitted to and from the device. The last parameter, pOverlapped, should be NULL when performing synchronous I/O. You'll examine this parameter in more detail shortly when asynchronous I/O is discussed.

Both ReadFile and WriteFile return TRUE if successful. By the way, ReadFile can be called only for devices that were opened with the GENERIC_ READ flag. Likewise, WriteFile can be called only when the device is opened with the GENERIC_WRITE flag.

Flushing Data to the Device

Remember from our look at the CreateFile function that you can pass quite a few flags to alter the way in which the system caches file data. Some other devices, such as serial ports, mailslots, and pipes, also cache data. If you want to force the system to write cached data to the device, you can call FlushFileBuffers:

BOOL FlushFileBuffers(HANDLE hfile); 

The FlushFileBuffers function forces all the buffered data associated with a device that is identified by the hfile parameter to be written. For this to work, the device has to be opened with the GENERIC_WRITE flag. If the function is successful, TRUE is returned.



Programming Server-Side Applications for Microsoft Windows 2000
Programming Server-Side Applications for Microsoft Windows 2000 (Microsoft Programming)
ISBN: 0735607532
EAN: 2147483647
Year: 2000
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net