660 · 用Read4从文件中读取N个字符 II-多次调用
描述
接口:int read4(char * buf)一次从文件中读取 4 个字符。
返回值是实际读取的字符数。 例如,如果文件中只剩下 3 个字符,则返回 3。
通过使用read4 接口,实现从文件读取 n 个字符的函数int read(char * buf,int n)。
样例1
输入:
“filetestbuffer”
read(6)
read(5)
read(4)
read(3)
read(2)
read(1)
read(10)
输出:
6, buf = “filete”
5, buf = “stbuf”
3, buf = “fer”
0, buf = “”
0, buf = “”
0, buf = “”
0, buf = “”
/* 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
*/
char[] buffer = new char[4] ;
int bufferPtr = 0 , bufferCnt = 0 ;
public int read(char[] buf, int n) {
// Write your code here
int ptr = 0 ;
while(ptr < n){
if(bufferPtr == bufferCnt){
bufferCnt = read4(buffer);
bufferPtr = 0 ;
}
if(bufferCnt == 0){
break ;
}
while(ptr < n && bufferPtr < bufferCnt){
buf[ptr++] = buffer[bufferPtr++] ;
}
}
return ptr ;
}
}