1.1 --- a/lib/__builtins__/file.py Mon Dec 12 23:33:28 2016 +0100
1.2 +++ b/lib/__builtins__/file.py Tue Dec 13 00:58:52 2016 +0100
1.3 @@ -20,16 +20,17 @@
1.4 """
1.5
1.6 from __builtins__.types import check_int, check_string
1.7 -from native import fclose, fopen, fread, fwrite
1.8 +from native import isinstance as _isinstance, fclose, fopen, fread, fwrite
1.9
1.10 class filestream:
1.11
1.12 "Generic file-oriented stream functionality."
1.13
1.14 - def __init__(self, bufsize=1024):
1.15 + def __init__(self, encoding=None, bufsize=1024):
1.16
1.17 - "Initialise the stream with the given 'bufsize'."
1.18 + "Initialise the stream with the given 'encoding' and 'bufsize'."
1.19
1.20 + self.encoding = encoding
1.21 self.bufsize = bufsize
1.22 self.__data__ = None
1.23
1.24 @@ -42,7 +43,7 @@
1.25 # Read any indicated number of bytes.
1.26
1.27 if n > 0:
1.28 - return fread(self.__data__, n)
1.29 + s = fread(self.__data__, n)
1.30
1.31 # Read all remaining bytes.
1.32
1.33 @@ -60,13 +61,26 @@
1.34 except EOFError:
1.35 pass
1.36
1.37 - return "".join(l)
1.38 + s = "".join(l)
1.39 +
1.40 + # Convert bytes to text if necessary.
1.41 +
1.42 + if self.encoding:
1.43 + return unicode(s, self.encoding)
1.44 + else:
1.45 + return s
1.46
1.47 def write(self, s):
1.48
1.49 "Write string 's' to the stream."
1.50
1.51 check_string(s)
1.52 +
1.53 + # Encode text as bytes if necessary.
1.54 +
1.55 + if self.encoding and _isinstance(s, utf8string):
1.56 + s = s.encode(self.encoding)
1.57 +
1.58 fwrite(self.__data__, s)
1.59
1.60 def close(self):
1.61 @@ -79,11 +93,14 @@
1.62
1.63 "A file abstraction."
1.64
1.65 - def __init__(self, filename, mode="r", bufsize=1024):
1.66 + def __init__(self, filename, mode="r", encoding=None, bufsize=1024):
1.67
1.68 - "Open the file with the given 'filename' using the given access 'mode'."
1.69 + """
1.70 + Open the file with the given 'filename' using the given access 'mode',
1.71 + any specified 'encoding', and the given 'bufsize'.
1.72 + """
1.73
1.74 - get_using(filestream.__init__, self)(bufsize)
1.75 + get_using(filestream.__init__, self)(encoding, bufsize)
1.76 self.__data__ = fopen(filename, mode)
1.77
1.78 def readline(self, size=None): pass