Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Using FALLOC_FL_PUNCH_HOLE from Python

View punch.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import ctypes
import ctypes.util
 
c_off_t = ctypes.c_int64
 
def make_fallocate():
libc_name = ctypes.util.find_library('c')
libc = ctypes.CDLL(libc_name)
 
_fallocate = libc.fallocate
_fallocate.restype = ctypes.c_int
_fallocate.argtypes = [ctypes.c_int, ctypes.c_int, c_off_t, c_off_t]
 
del libc
del libc_name
 
def fallocate(fd, mode, offset, len_):
res = _fallocate(fd.fileno(), mode, offset, len_)
if res != 0:
raise IOError(res, 'fallocate')
 
return fallocate
 
fallocate = make_fallocate()
del make_fallocate
 
FALLOC_FL_KEEP_SIZE = 0x01
FALLOC_FL_PUNCH_HOLE = 0x02
 
 
def main(db):
orig_data = ''.join(chr(i) for i in xrange(10))
format_ = lambda s: [ord(c) for c in s]
 
with open(db, 'w') as fd:
fd.write(orig_data)
 
with open(db, 'r') as fd:
data = fd.read()
print 'Original value:', format_(data)
 
print 'Punching hole at offset 2, length 3'
with open(db, 'a') as fd:
fallocate(fd, FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE, 2, 3)
 
print 'Reading file'
with open(db, 'r') as fd:
data = fd.read()
print 'New value:', format_(data)
 
if __name__ == '__main__':
main('punch.db')

That a great piece of code. Unfortunately I don't understand it in details so well that I could enhance it with my feature request personally, which is to allow to pipe input on the command line into the python script and get the result as a file. I'd be very happy to see that realized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.