# Read4

## Read N Characters Given Read4

The API: int read4(char \*buf) reads 4 characters at a time from a file.

By using the read4 API, implement the function int read(char \*buf, int n) that reads n characters from the file.

* create char\[] 接收API傳進來的資料

```python
def read(self, buf, n):
    idx = 0
    buf4 = [''] * 4
    while idx < n:
        num = read4(buf4)
        if num == 0:
            break
        i = 0
        #                讀進來沒那麼多
        while idx < n and i < num:
            buf[idx] = buf4[i]
            i+=1
            idx+=1        
    return idx
```

## Read N Characters Given Read4 II

The read function may be called multiple times.

Example 1:

Given buf = "abc" read("abc", 1) // returns "a"&#x20;

read("abc", 2); // returns "bc" read("abc", 1); // returns ""&#x20;

```python
def __init__(self):
    self.buf4 = [0] * 4
    self.buf4_size = 0
    self.buf4_idx = 0
        
        
def read(self, buf, n):
    idx = 0
    while idx < n:
        if self.buf4_idx == 0:
            self.buf4_size = read4(self.buf4)
            if self.buf4_size == 0: break
        
        #                        讀進來沒那麼多
        while idx < n and self.buf4_idx < self.buf4_size:
            buf[idx] = self.buf4[self.buf4_idx]
            idx+=1
            self.buf4_idx+=1
        
        #  需要重讀 read4   
        if self.buf4_idx >= self.buf4_size:
            self.buf4_idx = 0

    return idx
```
