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;
}
本文介绍了一种利用read4 API实现read函数的方法,该函数可以从文件中读取指定数量的字符。通过两次循环和临时缓冲区的方式确保了正确处理文件末尾的情况,并能应对多次调用的需求。
220

被折叠的 条评论
为什么被折叠?



