注意: CreateFile 跟 fopen 不同,打开文件时不区分 文本方式 或 二进制 方式 ReadFile 或 WriteFile 都是对二进制数据进行操作 HANDLE WINAPI CreateFile( __in LPCTSTR lpFileName, // 文件路径 __in DWORD dwDesiredAccess, // 访问权限,GENERIC_READ | GENERIC_WRITE __in DWORD dwShareMode, // 共享模式,NULL | FILE_SHARE_READ | FILE_SHARE_WRITE __in LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 安全属性 __in DWORD dwCreationDisposition, // 创建配置,CREATE_ALWAYS | CREATE_NEW | OPEN_ALWAYS | OPEN_EXISTING __in DWORD dwFlagsAndAttributes, // 扩展属性,NULL | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY __in HANDLE hTemplateFile // 指定一个文件句柄,新文件将从这个文件中复制扩展属性。NULL ); BOOL WINAPI ReadFile( __in HANDLE hFile, // 文件句柄 __out LPVOID lpBuffer, // 接收数据用的 buffer __in DWORD nNumberOfBytesToRead, // 要读取的字节数 __out LPDWORD lpNumberOfBytesRead, // 实际读取到的字节数 __in LPOVERLAPPED lpOverlapped // OVERLAPPED 结构,一般设定为 NULL ); BOOL WINAPI WriteFile( __in HANDLE hFile, // 文件句柄 __in LPCVOID lpBuffer, // 要写入的数据 __in DWORD nNumberOfBytesToWrite, // 要写入的字节数 __out LPDWORD lpNumberOfBytesWritten, // 实际写入的字节数 __in LPOVERLAPPED lpOverlapped // OVERLAPPED 结构,一般设定为 NULL ); DWORD WINAPI GetFileSize( __in HANDLE hFile, // 文件句柄 __out LPDWORD lpFileSizeHigh // high-order 的返回值,一般设定为 NULL ); 读文件: void read(const wchar_t* strPath) { HANDLE hFile = ::CreateFile(strPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, NULL, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD nFileSize = ::GetFileSize(hFile, NULL); char* lpBuffer = new char[nFileSize]; DWORD nNumberOfBytesRead; BOOL bRet = ::ReadFile(hFile, lpBuffer, nFileSize, &nNumberOfBytesRead, NULL); // TODO ... delete[] lpBuffer; CloseHandle(hFile); } } 写文件: void write(const wchar_t* strPath, const wchar_t* strContent, const int nContentSize) { HANDLE hFile = ::CreateFile(strPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, NULL, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD nNumberOfBytesWritten; ::WriteFile(hFile, strContent, nContentSize, &nNumberOfBytesWritten, NULL); // TODO ... CloseHandle(hFile); } }