# LeetCode: 157. 用 Read4 读取 N 个字符¶

## 1、题目描述¶

API read4 可以从文件中读取 4 个连续的字符，并且将它们写入缓存数组 buf 中。

参数类型: char[] buf



File file("abcdefghijk"); // 文件名为 "abcdefghijk"， 初始文件指针 (fp) 指向 'a'
char[] buf = new char[4]; // 创建一个缓存区使其能容纳足够的字符


参数类型:   char[] buf, int n



输入： file = "abc", n = 4



输入： file = "abcde", n = 5



输入： file = "abcdABCD1234", n = 12



输入： file = "leetcode", n = 5



1. 不能 直接操作该文件，文件只能通过 read4 获取而 不能 通过 read
2. read 函数只在每个测试用例调用一次。
3. 你可以假定目标缓存数组 buf 保证有足够的空间存下 n 个字符。

## 2、解题思路¶

• 目标文件少于目标字符数
• 目标字符数不能被4整除的处理

"""

@param buf, a list of characters
@return an integer

# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf = [' '] * 4 # Create buffer with enough space to store characters
read4(buf) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""
class Solution:

"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
temp = [0] * 4
temp_count = 0
count = n // 4
reminder = n % 4
res = 0

buf_point = 0

for i in range(count):
if temp_count:
res += temp_count
buf[buf_point:buf_point + temp_count] = temp[:temp_count]
buf_point += temp_count
temp_count = 0
else:
break

if reminder: