-5

I am a amateur programmer in C programming, I know how to read data directly from a drive (file = fopen("//./D:", "r"); ). Now I want to write data to the disk directly using the same way by changing the second argument of the mentioned function to "w". But it doesn't work even when I run the program as administrator. I was wondering:

  1. How to write data directly to a drive or flash drive using C?

  2. How the programs like Diskpart.exe write to a disk?

I am using Windows.

1 Answers1

2

Windows imposes special requirements for direct write access to disk volumes. You have to have administrative privileges and you have to take extra steps to demonstrate to the operating system that you are not going to overwrite the contents of a mounted file system (which could cause the entire computer to crash). fopen("//./D:", "w") does not take those extra steps. It appears to me that you can't do this with fopen, fread, fwrite, etc; you need to use the CreateFile, ReadFile, WriteFile, etc operating system primitives directly.

(As discussed in the Q&A that this is now closed as a duplicate of, the first of these "extra steps" is opening the device pathname for read and write access, even if you only mean to write -- GENERIC_READ|GENERIC_WRITE at the CreateFile level. fopen mode "w" supplies only GENERIC_WRITE to CreateFile. You also need to specify a particular disposition, sharing mode, file attributes, security attributes, etc.)

zwol
  • 135,547
  • 38
  • 252
  • 361