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 will only be called once for each test case.
API read4 返回所读字符的长度,可能是4,也可能比4小。调用read4 API 时需要传入char数组且长度为4.
read函数 返回所读字符的长度,也许是n,也许比n 小
public int read(char[] buf, int n) {
int cnt = 0;
char[] tmp = new char[4];
while (cnt < n) {
int len = read4(tmp);
if (len == 0) break;
int idx = 0;
while (cnt < n && idx < len) buf[cnt++] = tmp[idx++];
}
return cnt;
}
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.
因为要被调用多次, 每次 tmp_ptr 到达 len 的长度时要被清零。
char[] tmp = new char[4];
int tmp_ptr = 0;
int len = 0;
public int read(char[] buf, int n) {
int ptr = 0;
while (ptr < n) {
if (tmp_ptr == 0) {
len = read4(tmp);
}
if (len == 0) break;
while (ptr < n && tmp_ptr < len) {
buf[ptr++] = tmp[tmp_ptr++];
}
if (tmp_ptr == len) tmp_ptr = 0;
}
return ptr;
}