串⼝之ReadFileWriteFile函数详解
BOOL ReadFile(write的返回值
  HANDLE hFile, //⽂件的句柄
  LPVOID lpBuffer, //⽤于保存读⼊数据的⼀个缓冲区
  DWORD nNumberOfBytesToRead, //要读⼊的字符数
  LPDWORD lpNumberOfBytesRead, //指向实际读取字节数的指针
  LPOVERLAPPED lpOverlapped //如⽂件打开时指定了FILE_FLAG_OVERLAPPED,那么必须,⽤这个参数引⽤⼀个特殊的结构。该结构定义了⼀次异步读取操作。否则,应将这个参数设为NULL
  );
功能说明
  从⽂件指针指向的位置开始将数据读出到⼀个⽂件中, 且⽀持同步和异步操作,
  如果⽂件打开⽅式没有指明FILE_FLAG_OVERLAPPED的话,当程序调⽤成功时,它将实际读出⽂件的字节数保存到lpNumberOfBytesRead指明的地址空间中。
  如果⽂件要交互使⽤的话,当函数调⽤完毕时要记得调整⽂件指针。
  从⽂件中读出数据。与lread函数相⽐,这个函数要明显灵活的多。该函数能够操作通信设备、管道、套接字以及邮槽。
参数说明
  HANDLE hFile, 需要写⼊数据的⽂件指针,这个指针指向的⽂件必须是GENERIC_READaccess 访问属性的⽂件。
  LPOVERLAPPED lpOverlapped OVERLAPPED结构体指针,如果⽂件是以FILE_FLAG_OVERLAPPED⽅式打开的话,那么这个指针就不能为NULL。
返回值
  调⽤成功,返回⾮0
  调⽤不成功,返回为0
  会设置GetLastError。如启动的是⼀次异步读操作,则函数会返回零值,并将ERROR_IO_PENDING设置成GetLastError的结果。如结果不是零值,但读⼊的字节数⼩于nNumberOfBytesToRead参数指定的值,表明早已抵达了⽂件的结尾。
********************************************************************************************************************************
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 function is designed solely for asynchronous operation. It lets an application perform other processing during a file write operation.
BOOL WriteFile(  HANDLE,                    // handle to file  LPCVOID,                // data buffer  DWORD,    // number of bytes to write  LPDWORD,  // number of bytes written  LPOVERLAPPED        // overlapped buffer);
Parameters
hFile
[in] Handle to the file to be written to. The file handle must have been created with GENERIC_WRITE access to
the file.
Windows NT/2000/XP: For asynchronous write operations, hFile can be any handle opened with the
FILE_FLAG_OVERLAPPED flag by the function, or a socket handle returned by the or function.
Windows 95/98/Me: For asynchronous write operations, hFile can be a communications resource opened with
the FILE_FLAG_OVERLAPPED flag byCreateFile, or a socket handle returned by socket oraccept. 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 function.
Named pipe write operations across a network are limited to 65,535 bytes.
lpNumberOfBytesWritten
[out] Pointer to the variable that receives the number of bytes written. WriteFile sets this value to zero before
doing any work or error checking.
Windows NT/2000/XP: If lpOverlapped is NULL, lpNumberOfBytesWritten cannot be NULL. If lpOverlapped is not NULL, lpNumberOfBytesWritten can be NULL. If this is an overlapped write operation, you can get the number of bytes written by calling. If hFile is associated with an I/O completion port, you can get the number of bytes
written by calling.
If I/O completion ports are used and you are using a callback routine to free the memory allocated to the
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.
应⽤实例:
#include <stdio.h>#include <conio.h>#include <string.h>#define STRICT#define WIN32_LEAN_AND_MEAN#include <windows.h>void system_error(cha r *name){    char *ptr = NULL;    FormatMessage(        FORMAT_MESSAGE_ALLOCATE_BUFFER |        FORMAT_MESSAGE_FROM_SYSTEM,        0 ,        GetLastError(),        0,        (char *)&ptr,        1024,        NULL);    fprintf(stderr, "\nError %s: %s\n", name, ptr);    LocalFree(ptr);}int main(int argc, c har **argv){    int ch;    char buffer[1];    HANDLE file;    COMMTIMEOUTS timeouts;    DWORD read, written;    DCB port;    HANDLE keyboard = GetStd Handle(STD_INPUT_HANDLE);    HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);    DWORD mode;    char port_name[128] = "\\\\.\\COM3";
char init[] = ""; // e.g., "ATZ" to completely reset a modem.if ( argc > 2 )        sprintf(port_name, "\\\\.\\COM%c", argv[1][0]);    file = CreateFile(port_na me,        GENERIC_READ | GENERIC_WRITE,        0,        NULL,        OPEN_EXISTING,        0,        NULL);    if ( INVALID_HANDLE_VALUE == file) {        system_error("opening file");        return1;    }    memset(&port, 0, sizeof(port));    port.DCBlength = sizeof(port);    if ( !GetCommState(file, &port))        system_error("getting comm state");    if (!BuildCommDCB("baud=19200 parity=n data=8 stop=1", &port))        system_error("building comm DCB");    if  (!SetCommState(file, &port))        system_error("adjusting port settings");    timeouts.ReadIntervalTimeout = 1;    timeouts.ReadTotalTimeoutMultiplier = 1;    timeouts.ReadTotalTimeoutConstant = 1;    timeouts.WriteTotalTimeoutMultiplier = 1;    timeouts.WriteTotalTimeoutConstant = 1;    if (!SetCommTim eouts(file, &timeouts))        system_error("setting port time-outs.");    if (!GetConsoleMode(keyboard, &mode))        system_error("getting keyboard mode ");    mode &= ~ ENABLE_PROCESSED_INPUT;    if (!SetConsoleMode(keyboard, mode))        system_error("setting keyboard mode");    if (!EscapeCo mmFunction(file, CLRDTR))        system_error("clearing DTR");    Sleep(200);    if (!EscapeCommFunction(file, SETDTR))        system_error("setting DT R");    if ( !WriteFile(file, init, sizeof(init), &written, NULL))        system_error("writing data to port");    if (written != sizeof(init))        system_error("not all da ta written to port");    do {        // check for data on port an
d display it on screen.        ReadFile(file, buffer, sizeof(buffer), &read, NULL);        if ( read )            WriteFile(screen, buffer, read, &written, NULL);        // check for keypress, and write any out the port.if ( kbhit() ) {            ch = getch();            Wr iteFile(file, &ch, 1, &written, NULL);        }    } while ( ch != 127);.    CloseHandle(keyboard);    CloseHandle(file);    return0;}