Skip to content

Commit 65cf949

Browse files
authored
Update read-n-characters-given-read4.py
Your original code will not behave correctly if the input is "abcd", and n = 3. It'll save "abcd" to the buffer, where it should save only "abc" into buffer. The modification will allow it to do so.
1 parent 156b11e commit 65cf949

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

Python/read-n-characters-given-read4.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,17 @@ def read(self, buf, n):
3737
"""
3838
read_bytes = 0
3939
buffer = [''] * 4
40+
globalN = n
4041
for i in xrange(n / 4 + 1):
4142
size = read4(buffer)
4243
if size:
43-
buf[read_bytes:read_bytes+size] = buffer
44-
read_bytes += size
44+
toRead = min(globalN,size)
45+
buf[read_bytes:read_bytes+toRead] = buffer
46+
read_bytes += toRead
47+
globalN -= toRead
4548
else:
4649
break
47-
return min(read_bytes, n)
50+
return read_bytes
4851

4952
if __name__ == "__main__":
5053
global file_content

0 commit comments

Comments
 (0)