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.
Notes:
This question asks to use the read function multiple times. Thus, we need to record the position of previous calls. The solution is to use build-in variables: readPos is the current reading position; writePos is the position from the read4 API; and a buff[4] array to record the chars read previously.
The key logic are listed below,
1): when readPos == writePos, it is time to operate another call of read4 API;
2): if not, meaning that there are still some char left in previous call. Then we should start with the buff[4] array;
3): when writePos == 0, it means no more char left, so we should stop and return the actual number of chars read so far;
read4(buff) means store the chars read into buff. buff here serves as a cache from previous read4. Every time for a new call of read(), we need to check if there are chars remaining in the buff.
See the code below,
class Solution { public: int read(char *buf, int n) { for (int i = 0; i < n; ++i) { if (readPos == writePos) { writePos = read4(buff); readPos = 0; if (writePos == 0) return i; } buf[i] = buff[readPos++]; } return n; } private: int readPos = 0, writePos = 0; char buff[4]; };
No comments:
Post a Comment