How to read / write block device?

How to read / write block device? I heard that I read / write like a regular file, so I set up the loop device by doing

sudo losetup /dev/loop4 ~/file 

Then I ran the application in a file, then the loop device

 sudo ./a.out file sudo ./a.out /dev/loop4 

The file is executed perfectly. The loop device reads 0 bytes. In both cases, I got FP == 3 and turned off == 0. The file gets the line length correctly and prints the line when the loop gets me 0 and prints nothing

How to read / write to the block device?

 #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); } 
+5
source share
1 answer

It seems that losetup displays the file in 512 byte sectors. If the file size is not a multiple of 512, then the rest will be truncated.

When mapping a file from /dev/loopX to losetup , for a finish that is less than 512 bytes, it gives us the following warning:

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

For a file whose size cannot be divided by 512:

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

This warning has been added since util-linux ver 2.22 in this commit

+6
source

Source: https://habr.com/ru/post/1205408/


All Articles