WinApi学习笔记-读写文件

2022-05-09 11:08:38 浏览数 (2)

读文件

代码语言:javascript复制
#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 %dn",liFileSize.QuadPart);//???
	}
	while(true)
	{
		DWORD i;
		if(!ReadFile(hFileRead,lpFileDataBuffer,32,&dwReadSize,NULL))
		{
			printf("error while reading");
		}
		printf("read %d byten",&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;
}

写文件

代码语言:javascript复制
#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;
}

0 人点赞