Windows程序设计之创建、打开、读写文件方法介绍

一、创建或打开文件

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
);

二、读文件

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
);

三、写文件

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
);

四、示例代码

#include <Windows.h>
#include <iostream>
#include <tchar.h>
using namespace std;

int main(void)
{
	std::locale::global(std::locale("CHS"));

	HANDLE hFile = CreateFile(TEXT("C:\\Users\\xieyincai\\Desktop\\Demo.txt"), GENERIC_WRITE,
		FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		std::cout << "创建文件失败: " << GetLastError() << std::endl;
		return 1;
	}
	
	DWORD len1;
	TCHAR data1[] = TEXT("中华人民共和国 PK 美利坚合众国");
	BOOL bRet = WriteFile(hFile, data1, _tcslen(data1) * sizeof(TCHAR), &len1, NULL);
	if (!bRet)
	{
		std::cout << "写入文件失败" << GetLastError() << std::endl;
		return 1;
	}
	CloseHandle(hFile);

	hFile = CreateFile(TEXT("C:\\Users\\xieyincai\\Desktop\\Demo.txt"), GENERIC_READ,
		FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		std::cout << "打开文件失败: " << GetLastError() << std::endl;
		return 1;
	}

	DWORD len2;
	TCHAR data2[BUFSIZ] = { 0 };
	bRet = ReadFile(hFile, data2, BUFSIZ, &len2, NULL);
	if (!bRet)
	{
		std::cout << "读取文件失败" << GetLastError() << std::endl;
		return 1;
	}
	_tprintf(TEXT("%s\n"), data2);
	CloseHandle(hFile);
	
	return 0;
}

Leave a Reply

Your email address will not be published.