0

i know how to read/write a from/to a file in c using FILE pointer.But i want to go one step ahead and learn how to directly read/write to the disk partition.Also what is the difference between writing to a file and to a disk.Also can i manipulate the content already present on disk such as videos,images etc.

I am using C language on Linux 14.04 with gcc as my compiler.

TIA.

Sahil Chitnis
  • 35
  • 1
  • 5

1 Answers1

0

One of the nice things about UNIX/Linux systems is that pretty much anything you want to access is a file.

Linux has a /dev filesystem that has special files that are actually block and character devices. Among these are the raw disk partitions. If you run df -k, you'll see the devices associated with your currently mounted filesystems.

On one of my systems, this command outputs the following:

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/mapper/vg0-root   1040280    427008    560844  44% /
/dev/mapper/vg0-var    4161216   3275900    675604  83% /var
/dev/mapper/vg0-usr   30559268  14297456  14721716  50% /usr
/dev/mapper/vg0-prod  30526500  11905152  17082892  42% /prod
/dev/mapper/vg0-tmp    4161216    175168   3776336   5% /tmp
/dev/sda1               256681     28231    215196  12% /boot

From this example, we can see that the /var filesystem is associated with the special file /dev/mapper/vg0-var. So if you were to open that file, you would get access to the raw filesystem. Then you need to understand exactly how the filesystem is laid out to find what you're looking for.

Note that in order to do this, you need root access.

Warning!

It is generally a bad idea to access a mounted filesystem in this way. The OS caches writes to the filesystem, so what's physically on disk might not match what the OS says is there. Writing directly to a filesystem in this way can damage the filesystem because you are bypassing the OS's caching mechanisms.

Community
  • 1
  • 1
dbush
  • 205,898
  • 23
  • 218
  • 273