> For the complete documentation index, see [llms.txt](https://code.taozirui.com/lc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code.taozirui.com/lc/string/read-n-characters-given-read4-ii-call-multiple-times.md).

# 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 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:**&#x20;

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

**Example 2:**&#x20;

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

**Thoughts:**

Having a read4 index to indicate when to read, keep track the index until either the returned value from API is 0 or n is reached

```cpp
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
private:
    char buf4[4];
    int buf4Index = 4;
    int buf4Size = 4;

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 i = 0;
        while(i < n){
            // check calling API condition
            if(buf4Index >= buf4Size){
                buf4Size = read4(buf4);
                if(buf4Size == 0) break;
                buf4Index = 0;
            }
            buf[i] = buf4[buf4Index];
            i++;
            buf4Index++;
        }
        return i;
    }

};
```

**Java**

```java
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    private int ptr = 0;
    private int count = 0;
    private char[] buff = new char[4];
    public int read(char[] buf, int n) {
        int i = 0;
        while (i < n) {
            if (ptr == 0) {
                count = read4(buff);
            }
            if (count == 0) break;
            while (i < n && ptr < count) {
                buf[i++] = buff[ptr++];
            }
            if (ptr >= count) ptr = 0;
        }
        return i;
    }
}
```
