How to find CID of SD card in MFC application

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To find the CID (Card Identification) of an SD card in an MFC (Microsoft Foundation Class) application, you can use the Windows API functions and structures related to SD card communication. Here's a step-by-step guide on how to do this:

Step 1: Include the necessary header files and define the required constants:

cpp
#include <Windows.h>
#include <WinIoCtl.h>

Step 2: Define a function to get the CID of the SD card:

cpp
BOOL GetSdCardCid(DWORD dwDriveIndex, BYTE* pCidData, DWORD dwCidDataSize)
{
// Open a handle to the SD card
CString strDrive;
strDrive.Format(_T("\\\\.\\PhysicalDrive%d"), dwDriveIndex);
HANDLE hDevice = CreateFile(strDrive, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
return FALSE;
}

// Send the IOCTL command to retrieve the CID data
SD_CID sdCid;
DWORD dwBytesReturned;
BOOL bResult = DeviceIoControl(hDevice, IOCTL_SD_GET_CID, NULL, 0, &sdCid, sizeof(sdCid),
&dwBytesReturned, NULL);

CloseHandle(hDevice);

if (!bResult)
{
return FALSE;
}

// Copy the CID data to the output buffer
if (dwCidDataSize < sizeof(sdCid.CID))
{
return FALSE;
}

memcpy(pCidData, sdCid.CID, sizeof(sdCid.CID));

return TRUE;
}

Step 3: Call the function to get the CID:

cpp
void YourFunctionToGetSdCardCid()
{
// Specify the drive index of the SD card (e.g., 0 for the first SD card, 1 for the second, etc.)
DWORD dwDriveIndex = 0;

// Buffer to hold the CID data (16 bytes)
BYTE cidData[16];

if (GetSdCardCid(dwDriveIndex, cidData, sizeof(cidData)))
{
// Access the CID data here (in cidData)
// For example, you can convert it to a string and display it
CString strCid;
for (int i = 0; i < sizeof(cidData); i++)
{
CString strByte;
strByte.Format(_T("%02X"), cidData[i]);
strCid += strByte;
}

// Display the CID in a message box
AfxMessageBox(strCid);
}
else
{
// Failed to retrieve the CID
AfxMessageBox(_T("Failed to get SD card CID."));
}
}

In this example, the GetSdCardCid function opens a handle to the SD card, sends an IOCTL command to retrieve the CID data, and then copies the CID data to the output buffer provided by the caller. The YourFunctionToGetSdCardCid function is an example of how to call GetSdCardCid to get the CID of the SD card and display it in a message box.

Please note that you need appropriate privileges to access physical drives, and this code should be run with administrative privileges. Additionally, the IOCTL_SD_GET_CID constant used in the DeviceIoControl call may need to be adjusted depending on the specific SD card driver you are using.

Keep in mind that accessing the physical drives directly can have potential risks, so use caution when working with physical devices.