如何获取文件的设备块号

时间:2019-03-24 02:45:24

标签: linux ioctl

我正在使用下面的代码来获取文件的块号:

int get_block (int fd, int logical_block)
{
        int ret;
        ret = ioctl (fd, FIBMAP, &logical_block);
        if (ret <0 ){
                perror ("ioctl");
                return -1;
        }
        return logical_block;
}
int get_nr_blocks (int fd)
{
        struct stat buf;
        int ret,blocks_in_4k;
        ret = fstat (fd, &buf);
        if ( ret < 0 ) {
                perror ("fstat");
                return -1;
        }
        blocks_in_4k = buf.st_blocks/8;
        return blocks_in_4k;
}
void  print_blocks (int fd)
{
        int nr_blocks,i;
        int f_phys_block,e_phys_block;
        nr_blocks = get_nr_blocks (fd);
        if (nr_blocks <0 ) {
                fprintf (stderr, "get_nr_blocks failed!\n");
                return;
        }
        if (nr_blocks == 0) {
                printf( "no allocated blocks\n");
                return;
        } else if ( nr_blocks == 1)
                printf ("1 block\n\n");
        else
                printf ("this file has %d blocks\n\n",nr_blocks);

        for (i =0; i <nr_blocks; i++) {
                int phys_block;
                phys_block = get_block (fd, i );
                if (phys_block <0 ) {
                        fprintf (stderr, "get_block failed!\n");
                        return;
                }
                if ( !phys_block)
                        continue;
                if ( i == 0 )
                        f_phys_block=phys_block;
                if ( i == nr_blocks -1 )
                        e_phys_block=phys_block;
                printf ("(%u, %u),",i,phys_block);
        }
        if ( nr_blocks != e_phys_block - f_phys_block + 1) {
                printf ("\nthis file is fragmented \n");
                printf ("total blocks <%u>,first physical block <%u>, the last physical block <%u>\n",nr_blocks,f_phys_block,e_phys_block);
        }
        putchar ('\n');
}
int main (int argc, char *argv[] )
{
        int fd;
        if (argc <2 ) {
                fprintf (stderr, "usage: %s <file>\n",argv[0]);
        }
        fd = open (argv[1],O_RDONLY);
        if (fd <0) {
                perror ("open");
                return 1;
        }
        print_blocks(fd);
        return 0;
}

它给我这样的输出: 该文件有32个块(每个块4kb) (0,99596),(1,99597),(2,99598),(3,99599) 但是,当我使用命令dd制作了设备的映像后,该文件实际上已存储在该映像中,而块号并没有指示该文件的实际块偏移量。我该怎么做才能获得真实的设备块偏移量?

0 个答案:

没有答案