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);
}
}
#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);
}
}
댓글
댓글 쓰기