Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Low level disk operations in Linux for C++

What kind of methods exists in linux for low level disk operations in C++? I am attempting to write my own manager of data on a disk. For example, I would like to create a C++ program in the Linux environment that allocated a certain amount (continuous) on a disk and then freely allows me to read/write to that chunk of data. I don't think I want to use the standard fstream::open because then the file is managed by the OS and I might not get a continuous section on the disk.

Thanks.

like image 866
Matthew Avatar asked Nov 26 '12 19:11

Matthew


2 Answers

Generally, "low level" disk operations from user programs1 in Linux involve opening the disk special device. On my computer, these are called names like "/dev/sda" or "/dev/sda4" or even "/dev/disk/by-uuid/2a5150b4-71cb-11e1-b2fe-3b0d270b4e16".

You should take great care in choosing your device file. Writing to your system partition using this is not a good idea. Also, opening the device file needs root access in most cases (for obvious reasons).

The question of whether to use fstream is orthogonal. You may use std::fstream, fopen or even open to open the device. Then use whatever read operation matches the open that you did.

For your specific example, you might reconsider whether you need this functionality. Quoting Wikipedia, which in turn is quoting the Linux System Administrator Guide:

However, as the Linux System Administrator Guide states, "Modern Linux filesystem(s) keep fragmentation at a minimum by keeping all blocks in a file close together, even if they can't be stored in consecutive sectors. Some filesystems, like ext3, effectively allocate the free block that is nearest to other blocks in a file. Therefore it is not necessary to worry about fragmentation in a Linux system."


1 Since you mention C++, I assume you are writing a user program and not a device driver. Truly "low level" disk operations are available only inside the kernel. If you are, in fact, wanting to write a device driver, please restate your question to make that clear.

like image 62
Robᵩ Avatar answered Nov 19 '22 17:11

Robᵩ


I am not aware of any way to do this using standard Linux filesystems. I think you'll have to have a separate partition and do I/O directly on its dev pseudo-file (e.g. /dev/sda2).

like image 43
NPE Avatar answered Nov 19 '22 17:11

NPE