Window API (二)文件操作

    在Window API 中,创建和打开都用CreateFile只不过是用到的参数不同。DeleteFile、CopyFile、MoveFile就像字面理解那样,参数也比较随意。ReadFile读文件,WriteFile写文件。写个小程序练练:

   

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


DWORD ReadFileContent(LPSTR szFilePath)
{
	HANDLE hFileRead;
	LARGE_INTEGER liFileSize;	//LONGLONG
	DWORD dwReadedSize;
	LONGLONG liRealyRead = 0;
	BYTE lpFileDataBuffer[32];
	hFileRead= CreateFile(szFilePath,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,NULL);
	if(hFileRead == INVALID_HANDLE_VALUE)
	{
		printf("Open File false: %d\n",GetLastError());
	}
	if(!GetFileSizeEx(hFileRead,&liFileSize))
	{
		printf("get File Size error! %d\n",GetLastError());
	}
	else
	{
		printf("the size of file is %d\n",liFileSize.QuadPart);
	}
	while(TRUE)
	{
		DWORD i;
		if(!ReadFile(hFileRead,
			lpFileDataBuffer,
			32,
			&dwReadedSize,
			NULL))
		{
			printf("read error! %d\n" ,GetLastError());
			break;
		}
		printf("read %d ,content is :",dwReadedSize);
		for(i=0;i<dwReadedSize;i++)
		{
			printf("0x%x ",lpFileDataBuffer[i]);
		}
		printf("\n");
		liRealyRead+=dwReadedSize;
		if(liRealyRead==liFileSize.QuadPart)
		{
			printf("File read finished\n");
			break;
		}
	}
		CloseHandle(hFileRead);
		return 0;
}

DWORD SaveDataToFile(LPSTR szFilePath,
					 LPVOID lpData,
					 DWORD dwDataSize)
{
	HANDLE hFileWrite;
	DWORD dwWriteDataSize;
	hFileWrite=CreateFile(szFilePath,
		GENERIC_WRITE,
		0,
		NULL,
		OPEN_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if(hFileWrite == INVALID_HANDLE_VALUE)
	{
		printf("Open file Filed! %d\n",GetLastError());
	}
	SetFilePointer(hFileWrite,0,0,FILE_END);
	if(!WriteFile(hFileWrite,lpData,dwDataSize,&dwWriteDataSize,NULL))
		printf("write error! %d\n",GetLastError());
	else
		printf("write sueecss! , %d is writen!\n",dwWriteDataSize);
	CloseHandle(hFileWrite);
	return 0;
}

int main(int args,PCHAR arvg[])
{
	LPSTR szFileData=" 日日思君不见君,共饮长江水 ";
	SaveDataToFile("fsyData.txt",szFileData,lstrlen(szFileData));
	ReadFileContent("fsyData.txt");
	return 0;
}


   运行结果为:

write sueecss! , 28 is writen!
the size of file is 28
read 28 ,content is :0x20 0xc8 0xd5 0xc8 0xd5 0xcb 0xbc 0xbe 0xfd 0xb2 0xbb 0x
 0xfb 0xbe 0xfd 0xa3 0xac 0xb9 0xb2 0xd2 0xfb 0xb3 0xa4 0xbd 0xad 0xcb 0xae 0x

File read finished


  并在文件目录中产生一个名为 fsyData.txt 的文件,上书“日日思君不见君,共饮长江水”。

 

  本篇博客出自  阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/7066975

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值