Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ctype version #4

Open
trbs opened this issue May 8, 2014 · 1 comment
Open

ctype version #4

trbs opened this issue May 8, 2014 · 1 comment

Comments

@trbs
Copy link
Owner

trbs commented May 8, 2014

Below is a ctype's version of fallocate.
Not sure if it should be in its own project or if it should be included....

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')
@ctheune
Copy link

ctheune commented Aug 11, 2015

Thanks for this. This works nicely for me. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants