WinApi学习笔记-读写文件

读文件

#include <windows.h>
#include <stdio.h>
#include <iostream>

DWORD MyReadFile(LPSTR filePath)
{
	HANDLE hFileRead;
	LARGE_INTEGER liFileSize;
	DWORD dwReadSize;
	LONGLONG liTotalRead = 0;
	BYTE lpFileDataBuffer[32];

	hFileRead = CreateFile(
		filePath,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_ALWAYS,//有就打开,没有就创建
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);
	if(hFileRead == INVALID_HANDLE_VALUE)
	{
		printf("open error");
	}
	if(!GetFileSizeEx(hFileRead,&liFileSize))
	{
		printf("get size error");
	}
	else
	{
		printf("size is %d\n",liFileSize.QuadPart);//???
	}
	while(true)
	{
		DWORD i;
		if(!ReadFile(hFileRead,lpFileDataBuffer,32,&dwReadSize,NULL))
		{
			printf("error while reading");
		}
		printf("read %d byte\n",&dwReadSize);
		for(i = 0;i<dwReadSize;i++)
		{
			printf("  0x%x   ",lpFileDataBuffer[i]);
			std::cout<<lpFileDataBuffer[i]<<std::endl;
		}
		printf("\n");
		liTotalRead += dwReadSize;
		if(liTotalRead == liFileSize.QuadPart)
		{
			printf("end");
			break;
		}
	}
	CloseHandle(hFileRead);
	return 0;
}
int main()
{
	MyReadFile("c:\\a.txt");
	char a;
	std::cin >> a;
	return 0;
}



写文件

#include <windows.h>
#include <stdio.h>
#include <iostream>

DWORD MyWriteFile(LPSTR filePath,LPVOID lpData,DWORD dwSize)
{
	HANDLE hWrite;
	DWORD dwWriteSize;
	hWrite = CreateFile(filePath,GENERIC_WRITE,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if(hWrite == INVALID_HANDLE_VALUE)
	{
		printf("open error");
	}
	SetFilePointer(hWrite,0,0,FILE_END);//??
	if(!WriteFile(hWrite,lpData,dwSize,&dwWriteSize,NULL))
	{
		printf("error while writeing");
	}
	CloseHandle(hWrite);
	return 0;
}
int main()
{
	MyWriteFile("c:\\a.txt","myxland",lstrlen("myxland"));
	char a;
	std::cin >> a;
	return 0;
}
posted @ 2009-09-22 12:51  liulun  阅读(563)  评论(0编辑  收藏  举报