我是靠谱客的博主 默默皮卡丘,最近开发中收集的这篇文章主要介绍磁盘扇区数据的读取和写入,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

用sdk对磁盘扇区数据进行读取和写入,代码存在风险,请酌情。

//
// Written by beiyu , beiyuly@gmail.com
// Read and Write Sectors with sdk function, v1.0
// WriteSectors do the job of writing
// ReadSectors do the job of reading
// good luck!
//
#include <windows.h>
#include <winioctl.h>
#include <stdio.h>

#define MAX_BUFFER        65535
//
// 对磁盘扇区数据的写入 dwStartSector为逻辑开始位置 0开始
//
BOOL WriteSectors(BYTE bDrive, DWORD dwStartSector, WORD wSectors, LPBYTE lpSectBuff)
{
        if (bDrive < 0)
                return FALSE;

        char devName[] = ".//PHYSICALDRIVE0";
        devName[strlen(devName) - 1] = devName[strlen(devName) - 1] + bDrive;

        HANDLE hDev = CreateFile(devName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (hDev == INVALID_HANDLE_VALUE)
                return 0;

        SetFilePointer(hDev, 512 * dwStartSector, 0, FILE_BEGIN);

        DWORD dwCB;
        BOOL bRet = WriteFile(hDev, lpSectBuff, 512 * wSectors, &dwCB, NULL);
        CloseHandle(hDev);

        return bRet;
}

//
// 对磁盘扇区数据的读取 dwStartSector为逻辑开始位置 0开始
//
BOOL ReadSectors(BYTE bDrive, DWORD dwStartSector, WORD wSectors, LPBYTE lpSectBuff)
{
        if (bDrive < 0)
                return FALSE;

        char devName[] = ".//PHYSICALDRIVE0";
        devName[strlen(devName) - 1] = devName[strlen(devName) - 1] + bDrive;

        HANDLE hDev = CreateFile(devName, GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (hDev == INVALID_HANDLE_VALUE)
                return 0;

        SetFilePointer(hDev, 512 * dwStartSector, 0, FILE_BEGIN);

        DWORD dwCB;
        BOOL bRet = ReadFile(hDev, lpSectBuff, 512 * wSectors, &dwCB, NULL);
        CloseHandle(hDev);

        return bRet;
}

int main(int argc, char *argv[])
{
        char szOverBuffer[MAX_BUFFER] = {0};
        char szOverBuffer2[MAX_BUFFER] = {0};

        printf("/n----------ReadSectors BUFFER2----------/n");
        ReadSectors(0, 0, 128, (LPBYTE)szOverBuffer2);

        for(int i=0;i<MAX_BUFFER;i++)
        { 
                if(i%16==0)
                { 
                        printf("%04X: ",i);
                }
                printf("%02X ",(unsigned char)szOverBuffer2[i]);
                if(i%16==15)
                {
                        printf("/n");
                }
        }

        printf("/n----------WriteSectors BUFFER1----------/n");
        WriteSectors(0, 0, 128, (LPBYTE)szOverBuffer);

        return 1;       
}

最后

以上就是默默皮卡丘为你收集整理的磁盘扇区数据的读取和写入的全部内容,希望文章能够帮你解决磁盘扇区数据的读取和写入所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部