Advertisement
Guest User

Untitled

a guest
Nov 18th, 2012
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #define _GNU_SOURCE             /* See feature_test_macros(7) */
  2. #include <fcntl.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <linux/falloc.h>
  9. #include <unistd.h>
  10.  
  11. #define BLOCKSIZE 4096
  12.  
  13. int main(int argc, char** argv) {
  14.     ssize_t rsize;
  15.     int fh, result;
  16.     char buff[BLOCKSIZE], ebuff[BLOCKSIZE];
  17.     off_t curpos, pstart, psize;
  18.     int freed;
  19.  
  20.     if (argc < 2) {
  21.     printf("%s [file...]\n", argv[0]);
  22.     return 0;
  23.     }
  24.  
  25.     memset(ebuff, 0, BLOCKSIZE);    // prepare a block of 0's
  26.    
  27.     for (int i = 1; i < argc; i++) {
  28.     char* file=argv[i];
  29.     curpos = 0;
  30.     pstart = 0;
  31.     psize = 0;
  32.     freed = 0;
  33.  
  34.     fh = open(file, O_RDWR, O_NOATIME);
  35.     if (fh == -1) {
  36.         perror("open()");
  37.         return -1;
  38.     }
  39.    
  40.     printf("sparseifying %s ", file);
  41.     fflush(stdout);
  42.     while ((rsize = read(fh, buff, BLOCKSIZE)) > 0) {
  43.         result = memcmp(buff, ebuff,rsize);
  44.         if (result == 0) { // block is empty
  45.         if (pstart == 0) { // previous block as not empty?
  46.             pstart = curpos;
  47.             psize = rsize; // save for later punching
  48.         } else {
  49.             psize += rsize; // previous block was empty too, add size
  50.         }
  51.        
  52.         freed += rsize;
  53.         } else if (pstart) { // block is not empty and we have a block that we still need to punch
  54.         result = fallocate(fh, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, pstart, psize);
  55.         if (result == -1) {
  56.             perror("fallocate()");
  57.             return -1;
  58.         }
  59.         pstart = 0;
  60.         psize = 0;
  61.         }
  62.         curpos += rsize;
  63.     }
  64.  
  65.     if (pstart) { // still a block to do ?
  66.         result = fallocate(fh, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, pstart, psize);
  67.         if (result == -1) {
  68.         perror("fallocate()");
  69.         return -1;
  70.         }
  71.     }
  72.  
  73.     if (rsize == 0) {
  74.         printf("done. freed %i bytes\n", freed);
  75.         continue;
  76.     }
  77.     if (rsize == -1) {
  78.         perror("read()");
  79.         return -1;
  80.     }
  81.     }
  82.     return -1;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement