Hi all,
To anyone that has been following this thread. I managed to cobble together enough from other sites to be able to read a sector, make a change, and then store that buffer back at the same sector (note that one has to set the file pointer, read the sector, and then reset the file pointer to the same spot again before writing - this is hopefully common sense but I should say it just in case). This is just to probe to me that I can change the content of a particular sector. Now the fun begins!!!
I ended up getting rip of the fopen/fread/fwrite commands and used, much to everyone else's advice, createfile. I also had to lock the drive in order to gain write-access to the sectors. Still need to get the unlock working again; at the moment, I have to close the application for the SD card to appear in Windows Explorer, but that's not the end of the world.
The text file starting at address (address not sector; sector number being offset/512) 262144 contained the start address of the text file I had previously placed on the SD card with "testtesttest123" in the file. After running this routine, the content of the text file read "helloesttest123".
I should also point out that one of the stumbling points on this was that it didn't like it when I had the number of bytes to read as 1024 or 1023. As soon as a dropped this to 512, it started to work. More investigation required here.
I'm nowhere near to being a pro-C programmer, but I somehow manage to stumble through! It's not a great deal of code here but it's enough to now allow me to do everything else I want to do.
Note that j: is my SD card slot. Wo betide anyone who sets this to C: and starts writing to random sectors there!
The code (that worked) in toto is:
Code:
char buf[600]; // Multiple of sector size
long long offset = 262144; // Sector-aligned offset
BOOL bTest = FALSE;
DWORD dwNumRead = 0;
HANDLE hFile = CreateFile(
L"\\\\.\\j:",
(GENERIC_READ | GENERIC_WRITE),
(FILE_SHARE_READ | FILE_SHARE_WRITE),
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hFile == INVALID_HANDLE_VALUE)
{
Console::WriteLine("Failed to create drive access");
}
DWORD bytesReturned;
BOOL retDevIoCtrl = DeviceIoControl(
hFile,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&bytesReturned,
NULL
);
SetFilePointer(hFile, offset, 0, FILE_BEGIN);
ReadFile(hFile, buf, 512, &bytesReturned, 0);
buf[0] = 'h';
buf[1] = 'e';
buf[2] = 'l';
buf[3] = 'l';
buf[4] = 'o';
SetFilePointer(hFile, 262144, 0, FILE_BEGIN); // FILE_BEGIN
WriteFile(hFile, buf, 512, &bytesReturned, 0);
CloseHandle(hFile);
Best,
Jimbo