158. Read N Characters Given Read4 II

问题描述:

 

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.

Example 1: 

Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""

Example 2: 

Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""

解题思路:

这道题目是157. Read N Characters Given Read4的进阶版

要求能够接在上次的位置继续读取。

这道题我一开始也不是很明白,看了很多别人的解释,明白了一直以来我的误区。

在   int read4(char *buf);  中, buf是存储返回值的缓存, read4是从一个已存在的文件中读取字符。

同样的   read(char *buf, int n)  中 buf也是存储返回值的缓存。

我们可以用一个本地的buffer来存储使用read4读出来的内容,同时使用writePos来标识本地buffer的长度,readPos来记录上次在本地buffer读取到的位置。

同时使用for循环来将本地buffer的内容写入至要返回的buffer中。

需要注意的是,当使用read4只能读取到0个字符时,代表已经到达文件尾部,此时应直接返回已读的长度。

代码:

// 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) {
        for(int i = 0; i < n; i++){
            if(writePos == readPos){
                writePos = read4(local_buf);
                readPos = 0;
                if(writePos == 0){
                    return i;
                }
            }
            buf[i] = local_buf[readPos++];
        }
        return n;
    }
private:
    int writePos = 0;
    int readPos = 0;
    char local_buf[4];
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9287640.html