|
| 1 | +/** |
| 2 | + * The API: int read4(char *buf) reads 4 characters at a time from a file. |
| 3 | + * The return value is the actual number of characters read. For example, it |
| 4 | + * returns 3 if there is only 3 characters left in the file. |
| 5 | + * By using the read4 API, implement the function int read(char *buf, int n) |
| 6 | + * that reads n characters from the file. |
| 7 | + * |
| 8 | + * Note: The read function will only be called once for each test case. |
| 9 | + * |
| 10 | + * Tags: |
| 11 | + */ |
| 12 | +class ReadNGivenRead4 { |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Call only 1 time |
| 20 | + * Can reach n or end of file |
| 21 | + * if read4 returns size smaller than 4, it means end of file |
| 22 | + * the # of bytes read is the minimum of n - readBytes and size of read4 |
| 23 | + * Copy things in read4 buffer to output buffer |
| 24 | + * Update readBytes |
| 25 | + */ |
| 26 | + public int read(char[] buf, int n) { |
| 27 | + char[] buffer = new char[4]; |
| 28 | + int readBytes = 0; |
| 29 | + boolean eof = false; // flag |
| 30 | + |
| 31 | + while (!eof && readBytes < n) { |
| 32 | + int size = read4(buffer); // read4 is given |
| 33 | + if (size < 4) eof = true; // file end |
| 34 | + int bytes = Math.min(n - readBytes, size); // reach n or end of file |
| 35 | + // src, src pos, dest, dest pos, length |
| 36 | + System.arraycopy(buffer, 0, buf, readBytes, bytes); // copy to |
| 37 | + readBytes += bytes; |
| 38 | + } |
| 39 | + return readBytes; // can be n or smaller |
| 40 | + } |
| 41 | +} |
0 commit comments