Low level disk operations in Linux for C++

送分小仙女□ 提交于 2019-12-12 08:27:54

问题


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.


回答1:


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.




回答2:


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).




回答3:


You should use system calls. There's a list here: linux system calls



来源:https://stackoverflow.com/questions/13571596/low-level-disk-operations-in-linux-for-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!