在Linux for C ++中的低级磁盘操作 [英] Low level disk operations in Linux for C++

查看:225
本文介绍了在Linux for C ++中的低级磁盘操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C ++中的低级磁盘操作,linux中存在什么类型的方法?我试图在磁盘上写我自己的数据管理器。例如,我想在Linux环境中创建一个C ++程序,在磁盘上分配一定量(连续),然后自由地允许我读取/写入该数据块。我不认为我想使用标准 fstream :: open ,因为那么该文件是由操作系统管理,我可能不会得到一个连续的部分在磁盘上。 / p>

感谢。

解决方案

Linux中的用户程序 1 涉及打开磁盘专用设备。在我的电脑上,这些被称为/ dev / sda或/ dev / sda4或甚至/ dev / disk / by-uuid / 2a5150b4-71cb-11e1-b2fe-3b0d270b4e16。

b
$ b

您应该非常小心选择您的设备文件。使用这个写入你的系统分区不是一个好主意。此外,打开设备文件在大多数情况下需要root访问权限(由于显而易见的原因)。



是否使用 fstream 的问题是正交的。您可以使用 std :: fstream fopen 或甚至打开打开设备。然后使用与您所做的打开操作相匹配的任何读取操作。



对于特定示例,您可能需要重新考虑是否需要此功能。引用维基百科,其中引用了 Linux系统管理员指南


< blockquote>

但是,如Linux系统管理员指南所述,现代Linux文件系统通过将文件中的所有块保持在一起,保持碎片最小化,即使它们不能存储在一些文件系统,如ext3,有效地分配与文件中其他块最接近的空闲块,因此不必担心Linux系统中的碎片。








1 因为你提到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.

这篇关于在Linux for C ++中的低级磁盘操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆