1 #!/usr/bin/env python 2 3 """ 4 File objects. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from __builtins__.types import check_int, check_string 23 import native 24 25 class filestream: 26 27 "Generic file-oriented stream functionality." 28 29 def __init__(self, bufsize=1024): 30 self.bufsize = bufsize 31 32 def read(self, n=0): 33 34 "Read 'n' bytes from the stream." 35 36 check_int(n) 37 38 # Read any indicated number of bytes. 39 40 if n > 0: 41 return native._fread(self.__data__, n) 42 43 # Read all remaining bytes. 44 45 else: 46 l = [] 47 48 # Read until end-of-file. 49 50 try: 51 while True: 52 l.append(native._fread(self.__data__, self.bufsize)) 53 54 # Handle end-of-file reads. 55 56 except EOFError: 57 pass 58 59 return "".join(l) 60 61 def write(self, s): 62 63 "Write string 's' to the stream." 64 65 check_string(s) 66 native._fwrite(self.__data__, s) 67 68 def close(self): pass 69 70 class file(filestream): 71 72 "A file abstraction." 73 74 def __init__(self, filename, mode="r", bufsize=1024): 75 76 "Open the file with the given 'filename' using the given access 'mode'." 77 78 get_using(filestream.__init__, self)(bufsize) 79 self.__data__ = native._fopen(filename, mode) 80 81 def readline(self, size=None): pass 82 def readlines(self, size=None): pass 83 84 # vim: tabstop=4 expandtab shiftwidth=4