title: access denied error from WriteFile to physical disk, win7
body: <p>I am trying to write some data to an SD card from a specific physical sector. I received a code to do this from a company and they say it works ok on windows-xp. This is the same case with <a href="https://stackoverflow.com/questions/3600853/writefile-error-5-denied-access-under-win-vista-seven">WriteFile error #5 &quot;denied access&quot; under win Vista/seven</a><br>
  Here is the part writing the data to SD card (in my cae drv value is 'F'). Reading from others, I added locking and dismont but the lock fails (and dismount too). I'm not so familiar with windows programming. Can anybody tell me what's wrong in this code? Thanks for any help. (BTW I;m locking 3GiB)</p>
  
  <pre><code>u32 HDD_write(u8 drv, u32 SecAddr, u32 blocks, u8 *buf) 
  {
    u32 ret = 0;
    u32 ldistanceLow, ldistanceHigh, dwpointer, bytestoread, numread;
    char cur_drv[100];
    HANDLE g_hDevice;
  
    sprintf(cur_drv, "\\\\.\\%c:",drv); // , (u32)drv);
    g_hDevice = CreateFile(cur_drv, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  
    if(g_hDevice == INVALID_HANDLE_VALUE)
      return 0;
  
    // lock and dismount
    ret = LockFile(g_hDevice, 0, 0, 3 * 1023 * 1023 * 1023, 0);
    printf("ret = %d", ret);
    DeviceIoControl(g_hDevice, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, NULL, NULL);
    printf("error = %d", GetLastError());
  
    ldistanceLow = SecAddr &lt;&lt; 9;
    ldistanceHigh = SecAddr &gt;&gt; (32-9);
    dwpointer = SetFilePointer(g_hDevice, ldistanceLow, (long *)&amp;ldistanceHigh, FILE_BEGIN);
  
    if(dwpointer != 0xFFFFFFFF) {
      bytestoread = blocks * 512;
      ret = WriteFile(g_hDevice, buf, bytestoread, (unsigned long *)&amp;numread, NULL);
      if(ret)   ret = 1;
      else      {
          ret = 0;
          printf("error = %d", GetLastError());
      }
    }
  
    CloseHandle(g_hDevice);
    return ret;
  }
  </code></pre>