Windows NT以上系统异步读写硬盘的方法
今日整理硬盘无意发现刚学windows编程时写的一段代码,用于在windows下异步读写硬盘用的.
可能网上已经有类似的代码了,小弟在发一次,希望别有人用这做坏事.
打开硬盘有两个东西要知道,第一打开的文件名:\\\\.\\PHYSICALDRIVE0, 0代表第一块硬盘,依次1代表第二块硬盘...第二打开硬盘使用的参数OPEN_EXISTING是不可少的,至于为什么查MSDN.
先把代码发上来大家看看,读写速度还可以几秒就1G了,有空改成完成端口不知道会不会快点.
(注意以下代码不要用\\\\.\\PHYSICALDRIVE0试验,会把硬盘时的第一个G内容写成0,后果可想而知)
1 #include <Windows.h>
2
3 VOID CALLBACK MyIOCompletion(DWORD dwErrorCode,
4 DWORD dwNumberOfBytesTransfered,
5 LPOVERLAPPED lpOverlapped
6 );
7
8 BOOL ReadHardDisk(char* disk);
9
10 int __stdcall WinMain(IN HINSTANCE hInstance, IN HINSTANCE hPrevInstance, IN LPSTR lpCmdLine, IN int nShowCmd )
11 {
12 //ReadHardDisk("\\\\.\\PHYSICALDRIVE0");
13 ReadHardDisk("C:\\a.dat"); // 如果要试试,先建立文件,要不会出错
14
15
16
17 return 0;
18 }
19
20 VOID CALLBACK MyIOCompletion(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped )
21 {
22 //TRACE("write disk succeed.");
23 }
24
25 BOOL ReadHardDisk(char* disk)
26 {
27 HANDLE hHead;
28
29 hHead = CreateFile(disk, GENERIC_WRITE, FILE_SHARE_WRITE,
30 NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
31 if (INVALID_HANDLE_VALUE == hHead)
32 {
33 return FALSE;
34 }
35
36 BYTE *pbWrite = new BYTE[1024 * 1024]; // 1M
37 OVERLAPPED overlap;
38
39
40 for (int i = 0; i < 1024; i++) // 1024 也就是 1G
41 {
42 overlap.Offset = (1024 * 1024) * i;
43 overlap.OffsetHigh = 0;
44 overlap.hEvent = NULL;
45 WriteFileEx(hHead, pbWrite, 1024 * 1024, &overlap, MyIOCompletion);
46 while(WAIT_IO_COMPLETION != SleepEx(0, TRUE)) // 在这里可能加点东西做点别的事情
47 {
48 Sleep(0); // 切换下时钟
49 }
50 }
51
52 CloseHandle(hHead);
53 delete pbWrite;
54
55 return TRUE;
56 }
57
2
3 VOID CALLBACK MyIOCompletion(DWORD dwErrorCode,
4 DWORD dwNumberOfBytesTransfered,
5 LPOVERLAPPED lpOverlapped
6 );
7
8 BOOL ReadHardDisk(char* disk);
9
10 int __stdcall WinMain(IN HINSTANCE hInstance, IN HINSTANCE hPrevInstance, IN LPSTR lpCmdLine, IN int nShowCmd )
11 {
12 //ReadHardDisk("\\\\.\\PHYSICALDRIVE0");
13 ReadHardDisk("C:\\a.dat"); // 如果要试试,先建立文件,要不会出错
14
15
16
17 return 0;
18 }
19
20 VOID CALLBACK MyIOCompletion(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped )
21 {
22 //TRACE("write disk succeed.");
23 }
24
25 BOOL ReadHardDisk(char* disk)
26 {
27 HANDLE hHead;
28
29 hHead = CreateFile(disk, GENERIC_WRITE, FILE_SHARE_WRITE,
30 NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
31 if (INVALID_HANDLE_VALUE == hHead)
32 {
33 return FALSE;
34 }
35
36 BYTE *pbWrite = new BYTE[1024 * 1024]; // 1M
37 OVERLAPPED overlap;
38
39
40 for (int i = 0; i < 1024; i++) // 1024 也就是 1G
41 {
42 overlap.Offset = (1024 * 1024) * i;
43 overlap.OffsetHigh = 0;
44 overlap.hEvent = NULL;
45 WriteFileEx(hHead, pbWrite, 1024 * 1024, &overlap, MyIOCompletion);
46 while(WAIT_IO_COMPLETION != SleepEx(0, TRUE)) // 在这里可能加点东西做点别的事情
47 {
48 Sleep(0); // 切换下时钟
49 }
50 }
51
52 CloseHandle(hHead);
53 delete pbWrite;
54
55 return TRUE;
56 }
57
我最擅长从零开始创造世界,所以从来不怕失败,它最多也就让我一无所有。