如何读/写块设备?我听说我像普通文件一样读/写,所以我设置了一个循环设备
sudo losetup /dev/loop4 ~/file
Run Code Online (Sandbox Code Playgroud)
然后我在文件上运行应用程序然后循环设备
sudo ./a.out file
sudo ./a.out /dev/loop4
Run Code Online (Sandbox Code Playgroud)
文件执行得很完美.循环设备读取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);
}
Run Code Online (Sandbox Code Playgroud)
在losetup似乎映射512字节扇区的文件.如果文件大小不是512的倍数,那么其余的将被截断.
将文件映射到/dev/loopXwith时losetup,对于小于512字节的文件,它会给出以下警告:
Warning: file is smaller than 512 bytes;
the loop device may be useless or invisible for system tools.
Run Code Online (Sandbox Code Playgroud)
对于大小不能除以512的文件:
Warning: file does not fit into a 512-byte sector;
the end of the file will be ignored
Run Code Online (Sandbox Code Playgroud)
自此提交中的util-linux ver 2.22 以来添加了此警告