CreateFile、ReadFile、WriteFile和fread、fwrite两种读写文件的方法

相关函数的使用可以查看MSDN上的说明文档。本文只提供实例。


程序需包含:#include “Windows.h”文件


方法一、采用:CreateFile、ReadFile、WriteFile


DWORD dwFileSize = 0;

	BYTE* buffer = NULL;

	HANDLE hFile = INVALID_HANDLE_VALUE;

	hFile = CreateFile("D:\\12123.jpg",GENERIC_READ,
		               FILE_SHARE_READ,NULL,OPEN_EXISTING,
					   FILE_ATTRIBUTE_NORMAL,NULL);

	if (hFile == INVALID_HANDLE_VALUE)
	{
		CloseHandle(hFile);

		cout<<"Create File Failed !"<


方法二、采用fread、fwrite


DWORD dwFileSize = 0;

	WIN32_FIND_DATA FileInfo;

	ZeroMemory(&FileInfo,sizeof(WIN32_FIND_DATA));

	HANDLE hFind = INVALID_HANDLE_VALUE;

	hFind = FindFirstFile("D:\\12123.jpg",&FileInfo); 

	if(hFind != INVALID_HANDLE_VALUE) 
	{
		dwFileSize = FileInfo.nFileSizeLow ;
	}

	FindClose(hFind);

	BYTE* buffer = new BYTE[dwFileSize];

	if (buffer == NULL)
	{
		cout<<"Create buffer error !"<


你可能感兴趣的:(VC++文件操作)