驅動開發學習----文件操作

參考教程:楚狂人的《驅動編程基礎》

實現功能:文件拷貝,涉及文件操作的幾個基本函數:ZwCreateFile,ZwReadFile,ZwWriteFile

NTSTATUS MyCopyFile(PUNICODE_STRING target_path,PUNICODE_STRING source_path)
{
    HANDLE target=NULL,source=NULL;
    PVOID buffer=NULL;
    LARGE_INTEGER offset={0};
    IO_STATUS_BLOCK io_status={0};
    NTSTATUS status;
    OBJECT_ATTRIBUTES source_attributes,target_attributes;
    IO_STATUS_BLOCK io_status_source,io_status_target;
    int length;
    buffer=(PWCHAR)ExAllocatePoolWithTag(NonPagedPool,4096,'mMyM');
    if(buffer==NULL)
    {
	DbgPrint("allocate failed!");
    }
    do{
	//open source file
	InitializeObjectAttributes(&source_attributes,source_path,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL);  //爲了初始化object_attributes
         status=ZwCreateFile(&source,  //out
	GENERIC_READ|GENERIC_WRITE,
	&source_attributes,
	&io_status_source,     //out  返回結果
	NULL,
	FILE_ATTRIBUTE_NORMAL,
	FILE_SHARE_READ,  //執行期間別的操作訪問允許權限
	FILE_OPEN_IF,
	FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS|FILE_SYNCHRONOUS_IO_NONALERT,
	NULL,0);
     if(status==STATUS_SUCCESS)
	DbgPrint("open source success ~~\n");
     else
        DbgPrint("open source fail^^\n");
     //open target file
     InitializeObjectAttributes(&target_attributes,target_path,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL);          
     status=ZwCreateFile(&target,  //out
	GENERIC_READ|GENERIC_WRITE,
	&target_attributes,
	&io_status_target,     //out  返回結果
	NULL,
	FILE_ATTRIBUTE_NORMAL,
	FILE_SHARE_READ,  //執行期間別的操作訪問允許權限
	FILE_OPEN_IF,
	FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS|FILE_SYNCHRONOUS_IO_NONALERT,
	NULL,0);
     if(status==STATUS_SUCCESS)
	DbgPrint("open target success ~~\n");
     else
         DbgPrint("open target fail^^\n");

     while(1)
    {
         length=4*1024;
         status=ZwReadFile(source,NULL,NULL,NULL,
		&io_status,buffer,length,&offset,NULL);
         if(!NT_SUCCESS(status))
        {
		if(status==STATUS_END_OF_FILE)
			status=STATUS_SUCCESS;
			break;
        }
	length=io_status.Information;
	status=ZwWriteFile(
		target,NULL,NULL,NULL,&io_status,
		buffer,length,&offset,NULL);
		if(!NT_SUCCESS(status))
		         break;
		offset.QuadPart+=length;
    }
   }while(0);
    DbgPrint("%d\n",length);
	if(target!=NULL)
		ZwClose(target);
	if(source!=NULL)
		ZwClose(source);
	if(buffer!=NULL)
		ExFreePool(buffer);
	return STATUS_SUCCESS;
}


DriverEntry函數添加內容如下:

    NTSTATUS ntstatus;
    UNICODE_STRING src=RTL_CONSTANT_STRING(L"\\??\\D:\\a.dat");
    UNICODE_STRING tar=RTL_CONSTANT_STRING(L"\\??\\D:\\b.dat");
    ntstatus=MyCopyFile(&tar,&src);
    if(ntstatus!=STATUS_SUCCESS)
	DbgPrint("copy fail\n");
    else
	DbgPrint("copy successful\n");


 

發佈了32 篇原創文章 · 獲贊 7 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章