I'm trying to write to physical disk using Microsoft C's _sopen_s() function but it doesn't work at all. Here is my code:
Code-Listing 1:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <share.h>
#include <fcntl.h>
#include <io.h>
int main(int argc, char * argv[])
{
int drive_descriptor;
if((errno = _sopen_s(&drive_descriptor,"//./PhysicalDrive0", _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE)) != 0)
{
printf("Failed to open //./PhysicalDrive0 for writing : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
When I compile and run the code I get, as administrator :
Failed to open //./PhysicalDrive0 for writing : Invalid argument
And without the administrator privilege I get :
Failed to open //./PhysicalDrive0 for writing : Permission denied
I know writing to physical drive can be done because I found a C code that does the work online :
Code-Listing 2:
#include <windows.h>
#include <conio.h>
#include <stdio.h>
void main(){
DWORD dw;
char *pathToBin = "C:\\Users\\M\\Desktop\\data.bin";
HANDLE drive = CreateFile("\\\\.\\I:", GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (drive != INVALID_HANDLE_VALUE){
HANDLE binary = CreateFile(pathToBin, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (binary != INVALID_HANDLE_VALUE){
DWORD size = GetFileSize(binary, 0);
if (size > 0){
byte *mbr = new byte[size];
if (ReadFile(binary, mbr, size, &dw, 0)){
printf("Binary file successfuly read!\n");
//ok,not lets write the contents of the binary file,to the first sector of the drive
if (WriteFile(drive, mbr, size, &dw, 0)){
printf("First sector overritten successfuly!\n");
}
else
printf("Fatal error! Can't override 1st sector!\n");
}
else
printf("Error reading from binary file!\n");
}
else
printf("Invalid binary file!\n");
}
else{
printf("Can't find the binary file to read from!\n");
}
CloseHandle(binary);
}
else
printf("Administrator privileges required!\n");
CloseHandle(drive);
_getch();
}
I just don't want to use some foreign function that looks too different from what *nix operating systems have (open() function).