Advertisement
TShiva

index_descr_file

Aug 11th, 2017
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <sys/ioctl.h>
  7. #include <linux/fs.h>
  8.  
  9.  
  10. //get_block - для файла связанноо с заданным fd, возвращает физический блок, ассоциированный с logical_block
  11.  
  12. int get_block(int fd, int logical_block){
  13.     int ret;
  14.     ret = ioctl(fd, FIBMAP, &logical_block);//нужно для соответствующего типа устройства сделать
  15.     if(ret<0){
  16.         perror("ioctl");
  17.         return -1;
  18.     }
  19.     return logical_block;
  20. }
  21.  
  22. //get_nr_blocks возвращает количество логических блоков, занимаемых файлом связанным с fd
  23. int get_nr_blocks(int fd){
  24.     struct stat buf;
  25.     int ret;
  26.  
  27.     ret = fstat(fd,&buf);
  28.     if(ret < 0){
  29.         perror("fstat");
  30.         return -1;
  31.     }
  32.     return buf.st_blocks;
  33. }
  34. //print_blocks - для каждого логического блока, занимаемого файлом, ассоциированным с fd
  35. //выдает в стандартный вывод пару значений - (логич блок - физич блок)
  36. void print_blocks(int fd){
  37.     int nr_blocks, i;
  38.     nr_blocks = get_nr_blocks(fd);
  39.  
  40.     if(nr_blocks<0){
  41.         fprintf(stderr, "get_nr_blocks failed!\n");
  42.         return;
  43.     }
  44.  
  45.     if(nr_blocks==0){
  46.         printf("no allocated blocks\n");
  47.         return;
  48.     } else if (nr_blocks == 1)
  49.         printf("1 blocks\n\n");
  50.     else
  51.         printf("%d blocks \n\n", nr_blocks);
  52.  
  53.     for (int i = 0; i < nr_blocks;++i) {
  54.         int phys_blocks;
  55.         phys_blocks = get_block(fd,i);
  56.         if(phys_blocks<0){
  57.             fprintf(stderr, "get_blocks failed!\n");
  58.             return;
  59.         }
  60.         if (!phys_blocks)
  61.             continue;
  62.         printf("(%u, %u) ", i, phys_blocks);
  63.     }
  64.     putchar('\n');
  65. }
  66.  
  67. int main(int argc, char *argv[]) {
  68.     int fd;
  69.     if (argc<2){
  70.         fprintf(stderr,"usage %s <file>\n", argv[0]);
  71.     }
  72.  
  73.     fd = open(argv[1],O_RDONLY);
  74.     if (fd < 0){
  75.         perror("open");
  76.         return 1;
  77.     }
  78.     print_blocks(fd);
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement