LeetCode - 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 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;
};


你可能感兴趣的:(Leetcode,leetcode,file,string)