Read the buffer from file every time. After loop terminated, check whether the total lens is over 4.
Then use n - len (a negative number) to set the end char.
1 // Forward declaration of the read4 API. 2 int read4(char *buf); 3 4 class Solution { 5 public: 6 /** 7 * @param buf Destination buffer 8 * @param n Maximum number of characters to read 9 * @return The number of characters read 10 */ 11 int read(char *buf, int n) { 12 int len = 0, each = INT_MAX; 13 while (len < n && (each = read4(buf))) { 14 len += each; 15 buf += each; 16 } 17 if (len >= n) { 18 buf[n-len] = '\0'; 19 len = n; 20 } 21 return len; 22 } 23 };