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.
1 /* The Read4 API is defined in the parent class Reader4. 2 int Read4(char[] buf); */ 3 4 public class Solution : Reader4 { 5 6 private Queue<char> queue = new Queue<char>(); 7 8 /** 9 * @param buf Destination buffer 10 * @param n Maximum number of characters to read 11 * @return The number of characters read 12 */ 13 public int Read(char[] buf, int n) { 14 int count = 0; 15 16 while (count < n) 17 { 18 while (queue.Count > 0) 19 { 20 buf[count++] = queue.Dequeue(); 21 22 if (count == n) 23 { 24 return count; 25 } 26 } 27 28 var newBuf = new char[4]; 29 int total = Read4(newBuf); 30 31 if (total == 0) 32 { 33 // eof condtion 34 break; 35 } 36 37 // read into queue 38 for (int i = 0; i < total; i++) 39 { 40 queue.Enqueue(newBuf[i]); 41 } 42 } 43 44 return count; 45 } 46 }