【发布时间】:2014-10-24 02:44:42
【问题描述】:
如何读/写块设备?我听说我像普通文件一样读/写,所以我通过这样做来设置循环设备
sudo losetup /dev/loop4 ~/file
然后我在文件上运行应用程序,然后是循环设备
sudo ./a.out file
sudo ./a.out /dev/loop4
文件完美执行。循环设备读取 0 个字节。在这两种情况下,我得到 FP==3 和 off==0。文件正确获取字符串长度并打印字符串,而循环让我得到 0 并且不打印任何内容
如何读取/写入块设备?
#include <fcntl.h>
#include <cstdio>
#include <unistd.h>
int main(int argc, char *argv[]) {
char str[1000];
if(argc<2){
printf("Error args\n");
return 0;
}
int fp = open(argv[1], O_RDONLY);
printf("FP=%d\n", fp);
if(fp<=0) {
perror("Error opening file");
return(-1);
}
off_t off = lseek(fp, 0, SEEK_SET);
ssize_t len = read(fp, str, sizeof str);
str[len]=0;
printf("%d, %d=%s\n", len, static_cast<int>(off), str);
close(fp);
}
【问题讨论】:
-
您的
~/file有多大?对小文件执行losetup可能对系统工具无用或不可见。 -
@ymonad 一个句子,大约 40bytes。我尝试使用`dd if=/dev/zero of=~/file2 count=10K`创建一个新文件,然后用vi编辑它。它似乎工作。它只是因为我有一个小文件而忽略它还是在它
-
在我的环境中
losetup给我一个大文件警告:“警告:文件不适合 512 字节的扇区;文件末尾将被忽略” i> ,对于小文件:“警告:文件小于 512 字节;循环设备可能对系统工具无用或不可见。” .所以后者可能是正确的。 -
此警告似乎是从
util-linux2.22 版添加的。 github.com/karelzak/util-linux/commit/…
标签: c linux block-device