Why writing to //./PhysicalDrive0 with _sopen_s() not working

Paiku Han 21 Reputation points
2021-03-23T05:55:12.997+00:00

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

Note that PhysicalDrive0 is not the system drive and I'm not interested in using another function like CreateFile(). Only function that look similar to their POSIX counterpart (e.g. open(), write(), etc.) can be used as I want to make my code easily portable across platforms.

Also note that the code should be in C not C++. Unfortunately There is no C tag in Microsoft Q&A.

Developer technologies | C++
0 comments No comments
{count} votes

Accepted answer
  1. WayneAKing 4,931 Reputation points
    2021-03-23T08:07:50.077+00:00

    What happens if you use _O_RDONLY instead of _O_RDWR ?

    • Wayne

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.