1、CreateFile
创建或打开、返回对象句柄
HANDLE CreateFile(
LPCTSTR lpFileName, // 指向文件名的指针
DWORD dwDesiredAccess, // 访问模式(GENERIC_READ / GENERIC_WRITE)
DWORD dwShareMode, // 共享模式
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 指向安全属性的指针
DWORD dwCreationDisposition, // 如何创建
DWORD dwFlagsAndAttributes, // 文件属性
HANDLE hTemplateFile // 用于复制文件句柄
);
2、WriteFile
BOOL WriteFile(
HANDLE hFile, //文件句柄
LPCVOID lpBuffer, // 要写入的一个数据缓冲区
DWORD nNumberOfBytesToWrite, //要写入数据的字节数量
LPDWORD lpNumberOfBytesWritten, // 实际写入文件的字节数量
LPOVERLAPPED lpOverlapped // OVERLAPPED结构体指针,
// 如果文件是以FILE_FLAG_OVERLAPPED方式打开的话,那么这个指针就不能为
NULL
);
3、ReadFile
BOOL ReadFile(
HANDLE hFile, //文件的句柄
LPVOID lpBuffer, // 用于保存读入数据的一个缓冲区
DWORD nNumberOfBytesToRead, //要读入的字符数
LPDWORD lpNumberOfBytesRead, //指向实际读取字节数的指针
LPOVERLAPPED lpOverlapped //OVERLAPPED结构体指针,
// 如果文件是以FILE_FLAG_OVERLAPPED方式打开的话,那么这个指针就不能为NULL
);
#include <windows.h>
#include <cstdio>
int main()
{
HANDLE hFile;
DWORD nBytes;
//写入文件
hFile = CreateFile(("test.out"),
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
0,
NULL );
char msg[] = "Hello World!";
if( hFile != INVALID_HANDLE_VALUE )
{
WriteFile( hFile, msg, sizeof(msg)-1, &nBytes, NULL );
CloseHandle(hFile);
}
//读取文件
hFile = CreateFile(("test.out"),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
0,
NULL );
if( hFile != INVALID_HANDLE_VALUE )
{
char line[256]={0};
BOOL bResult;
bResult = ReadFile(hFile,
line,
sizeof(line),
&nBytes,
NULL) ;
if (nBytes != 0 )
{
printf("%s\r\n", line);
}
CloseHandle(hFile);
}
}