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.
Example
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"
Notice
The read
function may be called multiple times.
分析
这道题是一道非常经典的工程类的题目。在存储的设计实现中,为了提升性能,我们经常会将用户的读写请求按照固定的bufferSize下发下去,这样的话就涉及到用户的请求进行分片。也就是本题的考察问题,我们需要将用户的请求按照4Bytes分片读出。首先需要一个缓冲区来缓存4Bytes的内容,同时使用pos和remain来标记缓冲区目前指针的位置和剩余字节数,然后在处理用户请求时,如果用户需要的字节数n >= remain,首先copy缓冲区的剩余内容到buf,然后循环的按照4Byte读出并copy到buf,如果读不出内容则直接返回当前的total字节数。最后如果remain > n,说明此时缓冲区的内容可以直接copy需要的字节数到buf即可。
Code
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
Solution()
{
memset(buffer, 0, sizeof(buffer));
remain = 0;
pos = 0;
}
/**
* @param buf destination buffer
* @param n maximum number of characters to read
* @return the number of characters read
*/
int read(char *buf, int n) {
// Write your code here
int total = 0;
while (remain <= n)
{
memcpy(buf + total, buffer + pos, remain);
n = n - remain;
total += remain;
remain = read4(buffer);
pos = 0;
if (remain == 0)
return total;
}
if (remain > n)
{
memcpy(buf + total, buffer + pos, n);
total += n;
remain -= n;
pos += n;
}
return total;
}
private:
char buffer[4];
int remain;
int pos;
};
运行效率
Your submission beats 60.40% Submissions!