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

 

你可能感兴趣的:(api,File,null,Integer,byte)