Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebangin127/4fe7e6cf251366cb4449c08b79db9ee6 to your computer and use it in GitHub Desktop.
Save ebangin127/4fe7e6cf251366cb4449c08b79db9ee6 to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
void diskread(HANDLE hDevice, int disk_size,int& bad_sector)
{
char buf[512];
int numread;
int ldistanceHigh = 512;
OVERLAPPED ov;
LARGE_INTEGER nLarge;
DWORD dwvalue;
nLarge.QuadPart = 0;
ov.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
ov.Offset = nLarge.LowPart;
ov.OffsetHigh = nLarge.HighPart;
while (ReadFile(hDevice, buf, 512, NULL, &ov) == 0)
{
dwvalue = WaitForSingleObject(ov.hEvent, 200); //how much time will be the bad sector ??
if (dwvalue == WAIT_TIMEOUT) //if time out
{
bad_sector++;
}
dwvalue = GetLastError();
if (dwvalue == ERROR_IO_PENDING)
{
/*for (int i = 0; i < 12; i++)
{
printf("%c", buf[i]);
} */
//for checking this goes allright
}
//--------------------for showing------------------------------------------
system("cls");
printf("disk size : %d MB\n", disk_size);
printf("\t%.4f%% \nbad_sector : %d", (double)nLarge.QuadPart/20/disk_size, bad_sector);
//-------------------------------------------------------------------------
nLarge.QuadPart += 512;
ov.Offset = nLarge.LowPart;
ov.OffsetHigh = nLarge.HighPart;
}
}
typedef BOOL(WINAPI *P_GDFSE)(LPCTSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
int get_disk_size(void) {
BOOL fResult;
char *pszDrive = "C:"; //compute c drive
P_GDFSE pGetDiskFreeSpaceEx = NULL;
unsigned __int64 i64FreeBytesToCaller,
i64TotalBytes,
i64FreeBytes;
pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress(
GetModuleHandle("kernel32.dll"), "GetDiskFreeSpaceExA"
);
fResult = pGetDiskFreeSpaceEx(pszDrive,
(PULARGE_INTEGER)&i64FreeBytesToCaller,
(PULARGE_INTEGER)&i64TotalBytes,
(PULARGE_INTEGER)&i64FreeBytes);
if (!fResult)
{
printf("ERROR: Could not get free space for %s\n", pszDrive);
exit(GetLastError());
}
return i64TotalBytes / (1024 * 1024); //return total MB
}
int main(void)
{
char cur_drv[100];
char buf[512];
int ldistanceHigh = 0;
int disk_size = get_disk_size(); //size of c drive
sprintf_s(cur_drv, "\\\\.\\PhysicalDrive%d", 0); //which physicaldrive
HANDLE hDevice = CreateFile((LPCSTR)cur_drv, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING, 0);
if (hDevice == INVALID_HANDLE_VALUE){
printf("INVLIAD read"); return 0;
}
//SetFilePointer(hDevice, 0, (long *)&ldistanceHigh, FILE_BEGIN); //pointer set it can be useful
int bad_sector = 0;
diskread(hDevice, disk_size,bad_sector);
CloseHandle(hDevice);
return bad_sector;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment