如何读/写块设备?

时间:2014-10-24 02:44:42

标签: c linux block-device

如何读取/写入块设备?我听说我像普通文件一样读/写,所以我通过

设置了一个循环设备
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);
}

1 个答案:

答案 0 :(得分:5)

losetup似乎以512字节扇区映射文件。如果文件大小不是512的倍数,那么其余的将被截断。

使用/dev/loopX将文件映射到losetup时, 对于小于512字节的fiile,它会给我们以下警告:

Warning: file is smaller than 512 bytes;
 the loop device may be useless or invisible for system tools.

对于大小不能除以512的文件:

Warning: file does not fit into a 512-byte sector;
 the end of the file will be ignored

this commit

util-linux版本2.22以来添加了此警告