Problem
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.
Examples
Example 1
Input:
"filetestbuffer"
read(6)
read(5)
read(4)
read(3)
read(2)
read(1)
read(10)
Output:
6, buf = "filete"
5, buf = "stbuf"
3, buf = "fer"
0, buf = ""
0, buf = ""
0, buf = ""
0, buf = ""
Example 2
Input:
"abcdef"
read(1)
read(5)
Output:
1, buf = "a"
5, buf = "bcdef"
Solution
Method 1 - String Enumeration
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 ptr = 0;
private int count = 0;
private char[] buff = new char[4];
public int read(char[] buf, int n) {
int i = 0;
while (i < n) {
if (ptr == 0) {
count = read4(buff);
}
if (count == 0) break;
while (i < n && ptr < count) {
buf[i++] = buff[ptr++];
}
if (ptr >= count) ptr = 0;
}
return i;
}
}