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.
用一个临时数组buffer存每次读完的数据,start表示offset应该从global read数组里哪里开始写。每次读完了放进buffer,再写进read里面。最后记录一下count,如果count<4证明读完文件了不用再读了。
// use pointer start to indicate the current filling position in global char array read[].
// use a char array buffer[] of length 4 as an intermediate container for new characters just read, and later output these character to global char array read[]
public int read(char[] read, int n) {
char[] buffer = new char[4];
int start = 0;
while (start <= n - 1) {
int count = read4(buffer);
for (int i = 0; i < count && start <= n - 1; i++) {
read[start++] = buffer[i];
}
if (count < 4) {
break;
}
}
return start;
}
比如先call了n=3,然后call n=5,那么第一次就读入了4个char,第二次call应该把上一次的最后一个char拿来。也就是说要有个cache取缓存已读取的字符,然后从这个cache里面取。
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
private int buffPtr = 0;
private int buffCnt = 0;
private char[] buff = new char[4];
public int read(char[] buf, int n) {
int ptr = 0;
while (ptr < n) {
if (buffPtr == 0) {
buffCnt = read4(buff);
}
if (buffCnt == 0) break;
while (ptr < n && buffPtr < buffCnt) {
buf[ptr++] = buff[buffPtr++];
}
if (buffPtr >= buffCnt) buffPtr = 0;
}
return ptr;
}
}