diff --git a/glymur/lib/__init__.py b/glymur/lib/__init__.py index ba5915d..20fee5f 100644 --- a/glymur/lib/__init__.py +++ b/glymur/lib/__init__.py @@ -1,3 +1,4 @@ """This package organizes individual libraries employed by glymur.""" from . import openjp2 as _openjp2 from . import openjpeg as _openjpeg +from . import c diff --git a/glymur/lib/c.py b/glymur/lib/c.py new file mode 100644 index 0000000..7ae9fd6 --- /dev/null +++ b/glymur/lib/c.py @@ -0,0 +1,45 @@ +""" +Wraps fopen and fclose functions in libc. +""" + +import ctypes +import ctypes.util + +libc_path = ctypes.util.find_library('c') +C_LIB = ctypes.CDLL(libc_path) + +def fopen(filename, mode): + """Opens the file with the specified mode. + + Parameters + ---------- + filename : str + Path to filename. + mode : str + Specifies how the file is to be opened. + + Returns + ------- + fptr : ctypes.c_void_p + File pointer. + """ + C_LIB.fopen.restype = ctypes.c_void_p + C_LIB.fopen.argtypes = [ctypes.c_char_p, ctypes.c_char_p] + fptr = C_LIB.fopen(ctypes.c_char_p(filename.encode()), + ctypes.c_char_p(mode.encode())) + return fptr + +def fclose(fptr): + """Closes a file stream. + + Parameters + ---------- + fptr : ctypes.c_void_p + File pointer. + """ + C_LIB.fclose.argtypes = [ctypes.c_void_p] + C_LIB.fclose.restype = ctypes.c_int32 + status = C_LIB.fclose(fptr) + if status != 0: + raise IOError("Unable to close file.") +