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.
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.
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 (eg /dev/sda2
).
You should use system calls. There's a list here: linux system calls
链接地址: http://www.djcxy.com/p/11480.html上一篇: 如何减少数组和返回索引?