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 are only 3 characters left in the file.
read4
by using the API, implement the function that int read(char *buf, int n)
reads n characters from the file.
Note:
The read
function may be called multiple times.
Analysis:
Since The function can be called multiple times, we need to record the left over content in the buffer of read4, and put T Hem in some place. For the next call, we need to read content from the carry over buffer first.
Solution:
1 /*The read4 API is defined in the parent class Reader4.2 int read4 (char[] buf);*/3 4 Public classSolutionextendsReader4 {5 /**6 * @parambuf Destination Buffer7 * @paramN Maximum number of characters to read8 * @returnThe number of characters read9 */Ten One Public Char[] carry; A Public intindex; - - Public intReadChar[] buf,intN) { the intleft =N; - - //Put carry over to BUF, and destroy the carry over array! - if(carry!=NULL){ + while(Left>0 && index<carry.length) { -buf[n-left]=Carry[index]; +left--; Aindex++; at } - if(index>=carry.length) { -carry=NULL; -Index=-1; - } - } in - Char[] Tempbuf =New Char[4]; to while(left>0){ + intnum =read4 (TEMPBUF); - //If the read number is larger then what we need and then we just put the left number of chars into BUF. the //And put the rest chars into carry array. * if(num>Left ) { $carry =New Char[num-Left ];Panax Notoginseng for(inti=left;i<num;i++) -Carry[i-left] =Tempbuf[i]; theindex = 0; + } A the intEnd =math.min (num,left); + for(inti=0;i<end;i++){ -Buf[n-left] =Tempbuf[i]; $left--; $ } - - //If reach EOF. the if(left>0 && num<4) Break; - }Wuyi the returnN-Left ; - Wu } -}
Leetcode-read N characters Given Read4 II