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.
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int cnt = 0;
int sz;
if(buf_len > 0){
int mn = min(buf_len, n);
memcpy(buf, buffer, mn);
cnt += mn;
if(n < buf_len){
memcpy(buffer, buffer + n, buf_len - n);
}
buf_len -= mn;
}
int leftsz = 0;
while(cnt < n){
sz = read4(buffer);
memcpy(buf + cnt, buffer, min(n - cnt, sz));
leftsz = sz - min(n - cnt, sz);
cnt += min(n - cnt, sz);
if(sz < 4) break;
}
if(leftsz != 0){
buf_len = leftsz;
memcpy(buffer, buffer + sz - leftsz, leftsz);
}
return cnt;
}
char buffer[4];
int buf_len = 0;
};
本文详细介绍了如何通过调用read4 API来实现read函数,该函数用于从文件中读取n个字符。讨论了返回值的含义,并提供了一个类Solution的实现,包括内部缓冲区和相关操作。

750

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



