Read and write hard disk sector directly and efficiently [duplicate]

感情迁移 提交于 2019-11-26 18:32:44

问题


I have a special need for block data storage. My data are formatted data blocks in size of 4096. For high efficiency, I want to directly manipulate the block on hard disk sector and do not want to treat the data block as file. I think one way is to treat the device as a file such as /dev/sda1 and to use lseek() read() and write() to read and write data. However I do not know the whether the head of the file is the first sector of hard disk. I also suspect the efficiency of this method.

I am working on Linux OS and C programming language.

What is the most efficient way to handle the sector of hard disk? Should I write an block device module of linux. However, I do not know much about it. What kernel functions should I use to read and write on block device?


回答1:


"Blocks in size of 4096" is not a special need, and you have not mentioned any access patterns that would break the kernel's built-in caching mechanisms.

The most efficient way to read and write your data is to use a file.




回答2:


int ReadSector(int numSector,char* buf)
{
    int retCode = 0;
    BYTE sector[512];
    DWORD bytesRead;
    HANDLE device = NULL;

    device = CreateFile("\\\\.\\H:",    // Drive to open
        GENERIC_READ,           // Access mode
        FILE_SHARE_READ,        // Share Mode
        NULL,                   // Security Descriptor
        OPEN_EXISTING,          // How to create
        0,                      // File attributes
        NULL);                  // Handle to template

    if(device != NULL)
    {
        // Read one sector
        SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;

        if (!ReadFile(device, sector, 512, &bytesRead, NULL))
        {
            Print("Error in reading1 floppy disk\n",numligne++);
        }
        else
        {
            // Copy boot sector into buffer and set retCode
            memcpy(buf,sector, 512);retCode=1;
        }

        CloseHandle(device);
        // Close the handle
    }

    return retCode;
}

This my function to read sectors and it is same maner to write. Sector zero will be first sector of a partition



来源:https://stackoverflow.com/questions/20161208/read-and-write-hard-disk-sector-directly-and-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!