The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function may be called multiple times.
思路:157的followup,需要用一個(gè)buf來存儲(chǔ)上一次read4讀入的字符,bufptr記錄上一次讀到的位置,bufsize記錄上一次read4讀入buf的大小,通過這三個(gè)變量可以在多次讀入的時(shí)候知道每次該從上一次的哪里繼續(xù)讀入字符,以及何時(shí)再調(diào)用read4獲取下一批字符。
int remainSize = 0;
int remainIndex = 0;
char[] remainBuf = new char[4];
public int read(char[] buf, int n) {
if (n <= 0) {
return 0;
}
int index = 0;
while (index < n) {
while (remainIndex < remainSize) {
buf[index++] = remainBuf[remainIndex++];
}
if (remainIndex >= remainSize) {
remainIndex = 0;
remainSize = read4(remainBuf);
}
if (remainSize == 0) {
break;
}
}
return index;
}