157. Read N Characters Given Read4
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 theread4
API, implement the functionint read(char *buf, int n)
that readsncharacters from the file.
Note:
Theread
function will only be called once for each test case.
int read(char *buf, int n) {
int result = 0;
while (n > 0) {
int cur = min(read4(buf), n);
result += cur;
buf += 4;
n -= 4;
}
return result;
}
158. Read N Characters Given Read4 II - Call multiple times
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 theread4
API, implement the functionint read(char *buf, int n)
that readsncharacters from the file.
Note:
Theread
function may be called multiple times.
S: external buffer vs. internal buffer
当上一次read4()读了四个数,文件系统指针已经移动到了四个位置以后, 当前用到k < 4时, 需要用internal buffer存储k以后的信息,下次从k + 1开始读而不是四个位置之后
int read4(char *buf);
class Solution {
public:
int read(char *buf, int n) {
int idx = 0;
while(idx < n) {
if (buffPtr == buffCnt) { //already wrote all cached value, start another read4
buffPtr = 0;
buffCnt = read4(buf4);
if (buffCnt == 0) break;
}
buf[idx++] = buf4[buffPtr++];
}
return idx;
}
private:
char buf4[4];
int buffPtr = 0;
int buffCnt = 0;
};