Friday 15 April 2011

c - How do I read/write a block device? -



c - How do I read/write a block device? -

how read/write block device? heard read/write normal file setup loop device doing

sudo losetup /dev/loop4 ~/file

then ran app on file loop device

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

the file executed perfectly. loop device reads 0 bytes. in both cases got fp==3 , off==0. file correctly gets string length , prints string while loop gets me 0 , prints nothing

how read/write 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"); homecoming 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); }

the losetup seems map file in 512-byte sectors. if file size not multiples of 512, rest truncated.

when mapping file /dev/loopx losetup, fiile smaller 512 bytes gives next warning:

warning: file smaller 512 bytes; loop device may useless or invisible scheme tools.

for file size cannot divided 512:

warning: file not fit 512-byte sector; end of file ignored

this warning added since util-linux ver 2.22 in this commit

c linux block-device

No comments:

Post a Comment