Advertisement
Guest User

Untitled

a guest
Jan 14th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <assert.h>
  2. #include <cstdio>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5.  
  6. int main(int argc, char** argv) {
  7.     FILE* file = fopen("myfile.dat", "wb");
  8.     // uint8_t* buf = (uint8_t*)malloc(1024 * 1024);
  9.     // fwrite(buf, 1, 1024*1024, file);
  10.  
  11.     fstore_t fst = { F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, 1024 * 1024 /* 1 MB */, 0 };
  12.     if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
  13.        fst.fst_flags = F_ALLOCATEALL;
  14.        assert(fcntl(fileno(file), F_PREALLOCATE, &fst) != -1);
  15.     }
  16.     // $ ls -la myfile.dat
  17.     // -rw-r--r--  1 me  staff  128 Jan 13 13:43 myfile.dat
  18.     // $ du -ch myfile.dat
  19.     // 1.0M myfile.dat
  20.     // 1.0M total
  21.  
  22.     fpunchhole_t fph = { 0, 0, 4096, 1024 * 1024 - 4096 };
  23.     assert(-1 != fcntl(fileno(file), F_PUNCHHOLE, &fph));
  24.     ftruncate(fileno(file), 128); // truncate file down to 128 bytes
  25.     assert(-1 != fcntl(fileno(file), F_PUNCHHOLE, &fph));
  26.     fclose(file);
  27.     // $ ls -la myfile.dat
  28.     // -rw-r--r--  1 me  staff  128 Jan 13 13:43 myfile.dat
  29.     // $ du -ch myfile.dat
  30.     // 1.0M myfile.dat
  31.     // 1.0M total
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement