How to align sectors for unbuffered writes

The following C++ example shows how to align sectors for unbuffered file writes. The Size variable is the size of the original data block you are interested in writing to the file.

#include <windows.h>

#define ROUND_UP_SIZE(Value,Pow2) ((SIZE_T) ((((ULONG)(Value)) + (Pow2) - 1) & (~(((LONG)(Pow2)) - 1))))

#define ROUND_UP_PTR(Ptr,Pow2)  ((void *) ((((ULONG_PTR)(Ptr)) + (Pow2) - 1) & (~(((LONG_PTR)(Pow2)) - 1))))


void main()
{
// Function code

    DWORD BytesPerSector = 0; // obtained from the GetFreeDiskSpace function.
    DWORD Size = 0; // buffer size of your data to write

// ... obtain data here
// sample data
    BytesPerSector = 65536;
    Size = 15536;
//

   // Ensure you have one more sector than Size would require.
   SIZE_T SizeNeeded = BytesPerSector + ROUND_UP_SIZE(Size, BytesPerSector);
 
   // Replace this statement with any allocation routine.
   LPBYTE Buffer = (LPBYTE) malloc(SizeNeeded);

   // Error checking of your choice.
   if ( !Buffer )
   {
     goto cleanup;
   }

   // Actual alignment happens here.
   void * BufferAligned = ROUND_UP_PTR(Buffer, BytesPerSector);

   // Add code using BufferAligned here.


cleanup:

   if ( Buffer )
   {
      // Replace with corresponding free routine.
      free(Buffer);
   }

}

댓글

이 블로그의 인기 게시물

[WinAPI] 모달리스 다이얼로그 설명

[WinDbg] Debugging a stack overflow

[WinDbg] first-chance, second-chance Exception