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
- Some operating systems restrict direct access to volumes (e.g. Windows)
- Writing errors as well as writing the wrong data into certain blocks
might result in filesystem corruption (loss of data on the HDD). - Antivirus-Software might flag it as suspicious code.
This question is oriented more theoretical.
The C language has access to files with functions
fopen/fclose/fread/fwriteetc. 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/writeto 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
CreateFilefunction with the device name\\.\PhysicalDrive0,\\.\C:or such.