4

I need to do a complete format on a USB stick (FAT16 or FAT32), put a file on the drive, then delete it and recover the file using a C program.

Could anyone give me a hint on what should I use to accomplish this?

I understand the layouts of the FAT16/32 filesystems, the problem is that I don't know how to access the raw HD data using C (since I can't use things like fopen or mmap because the file isn't there anymore).

Álvaro
  • 269
  • 1
  • 9
  • I have set a bounty on a similar question [CreateFile: direct write operation to raw disk “Access is denied” - Vista, Win7](http://stackoverflow.com/q/8694713/341970). Could you help me? – Ali Jan 03 '12 at 20:37

2 Answers2

8

This is highly operating system specific.

For Linux, you would open the raw device /dev/sdxx. Note that there are privilege hoops to manage.

For Windows, you would use something like:

 HANDLE h = CreateFile ("\\\\.\\PhysicalDriveX", GENERIC_READ,
                    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                    OPEN_EXISTING,
                    FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS,
                    NULL);

where X depends on the device.

sarnold
  • 99,632
  • 21
  • 173
  • 228
wallyk
  • 55,472
  • 16
  • 84
  • 144
2

Just use normal filesystem operations on the disk device.

This means you need to identify the disk device first, of course. But once opened, you can even mmap() it.

fge
  • 114,841
  • 28
  • 237
  • 319
  • " But once opened, you can even mmap() it." Can you please show a working example? mmap() - ing "\\\\.\\PhysicalDriveX" fails. – Laszlo Jan 19 '20 at 18:59