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 from native import isinstance as _isinstance, fclose, fopen, fread, fwrite 24 25 class filestream: 26 27 "Generic file-oriented stream functionality." 28 29 def __init__(self, encoding=None, bufsize=1024): 30 31 "Initialise the stream with the given 'encoding' and 'bufsize'." 32 33 self.encoding = encoding 34 self.bufsize = bufsize 35 self.__data__ = None 36 37 def read(self, n=0): 38 39 "Read 'n' bytes from the stream." 40 41 check_int(n) 42 43 # Read any indicated number of bytes. 44 45 if n > 0: 46 s = fread(self.__data__, n) 47 48 # Read all remaining bytes. 49 50 else: 51 l = [] 52 53 # Read until end-of-file. 54 55 try: 56 while True: 57 l.append(fread(self.__data__, self.bufsize)) 58 59 # Handle end-of-file reads. 60 61 except EOFError: 62 pass 63 64 s = "".join(l) 65 66 # Convert bytes to text if necessary. 67 68 if self.encoding: 69 return unicode(s, self.encoding) 70 else: 71 return s 72 73 def write(self, s): 74 75 "Write string 's' to the stream." 76 77 check_string(s) 78 79 # Encode text as bytes if necessary. When the encoding is not set, any 80 # original encoding of the text will be applied. 81 82 if _isinstance(s, utf8string): 83 s = s.encode(self.encoding) 84 85 fwrite(self.__data__, s) 86 87 def close(self): 88 89 "Close the stream." 90 91 fclose(self.__data__) 92 93 class file(filestream): 94 95 "A file abstraction." 96 97 def __init__(self, filename, mode="r", encoding=None, bufsize=1024): 98 99 """ 100 Open the file with the given 'filename' using the given access 'mode', 101 any specified 'encoding', and the given 'bufsize'. 102 """ 103 104 get_using(filestream.__init__, self)(encoding, bufsize) 105 self.__data__ = fopen(filename, mode) 106 107 def readline(self, size=None): pass 108 def readlines(self, size=None): pass 109 110 # vim: tabstop=4 expandtab shiftwidth=4