How can I write to any block on my HDD using the C programming language?
There was a question about writing the MBR but it didn't cover the C aspects that much.
Since filedescriptors are - as the word says - for files, I guess there is no way to use them in this case. The Low-level I/O included in the C standard library is also implemented with filedescriptors.
To put it more precisely:
This question is rather about writing HDD blocks than files (OS independent).
The answers to the question mentioned above basically suggested using dd (coreutils) on UNIX-Systems. This is why I am asking for a way in C. Maybe bootloaders (GRUB) and boot sector viruses use different techniques?
I guess changing the actual pointer inside of a filedescriptor is not a legitimate way.
Problems and limitations:
I know that there are certain aspects to keep in mind, such as
This question is oriented more theoretical.
The C language has access to files with functions fopen/fclose/fread/fwrite
etc. But there is no such thing as a block device in the language (not even a device, for that matter).
POSIX on the other hand has the low level functions open/close/read/write
to access to files, and have the concept of block device. These functions can be used (with care) for a block device, as long as you follow a few simple rules (block alignment, mainly) and you know the name of your device (/dev/xxx
).
If you are in a non-POSIX system, such as Windows, then the OS will have a specific way to handle the block device access. In Windows, for example, you can use the CreateFile
function with the device name \\.\PhysicalDrive0
, \\.\C:
or such.