Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 504
chenatu Avatar asked Nov 23 '13 10:11

chenatu


2 Answers

"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.

like image 69
CL. Avatar answered Sep 30 '22 20:09

CL.


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

like image 44
Daniel Avatar answered Sep 30 '22 18:09

Daniel