Skip to main content

A Dangerous C Disk-Write Example and How to Study It Safely

· 2 min read
Apache Wangye
Software developer and technical writer

This early C exercise demonstrates how a program can open a Windows physical drive and overwrite its first sector.

Warning: the original code can corrupt critical disk structures, make the operating system unbootable, and cause permanent data loss. Do not run it on a real machine or any disk containing valuable data. It is retained here only as a security-education example. A safe exercise should replace the physical-drive path with an ordinary test file inside an isolated virtual machine.

#include <stdio.h>
#include <stdlib.h>

int main()
{
char buffer[512] = "0";
FILE *fd = fopen("\\\\.\\PHYSICALDRIVE0", "rb+");
if (fd == NULL)
return 0;

fseek(fd, 0, SEEK_SET);
fwrite(buffer, 512, 1, fd);
printf("hello, your disk has been modified!\n");
fclose(fd);
return 0;
}

Why the code is dangerous

\\.\PHYSICALDRIVE0 refers to the first physical disk on Windows rather than to a normal file. The program requests read/write access, seeks to byte zero, and writes 512 bytes. Depending on the disk layout, that area may contain a master boot record, partition metadata, or other structures needed to locate data.

Modern Windows versions normally require elevated privileges for raw-disk access, but permission checks are not a safety mechanism for experimental code. Running the program as an administrator can still cause immediate damage.

A safe replacement

To study file positioning and binary writes, change the target to a disposable file:

FILE *fd = fopen("disk-image.bin", "wb+");

Create the file in a temporary directory, write known bytes, and inspect it with a hex editor. This preserves the learning objective—understanding fopen, fseek, and fwrite—without touching a physical device.

Page views: --

Total views -- · Visitors --