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傳進來的資料

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"

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

Last updated

Was this helpful?