Problem
Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.
Method read4:
The API read4 reads 4 consecutive characters from the file, then writes those characters into the buffer array buf.
The return value is the number of actual characters read.
Note that read4() has its own file pointer, much like FILE *fp in C.
Definition of read4:
1 | |
Below is a high level example of how read4 works:
1 | |
Method read:
By using the read4 method, implement the method read that reads n characters from the file and store it in the buffer array buf. Consider that you cannot manipulate the file directly.
The return value is the number of actual characters read.
Definition of read:
1 | |
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Example 4:
1 | |
Note:
- Consider that you cannot manipulate the file directly, the file is only accesible for
read4but not forread. - The
readfunction will only be called once for each test case. - You may assume the destination buffer array,
buf, is guaranteed to have enough space for storing n characters.
Explanation
-
This problem is asking us to use method
read4to implement methodread. In thereadmethod, the maximum size we can read isn, and the read data should store inbuf, and every read operation, the data inbufwill refresh. -
First, we create a counter
total, andchar[4] tempBufto store the data usingread4(tempBuf), then ifread4’s return numbernumReadis not 0, then we loop from 0 tonumReadexclusive to store the data intempBuftobuf[total+i]. Since the maximum number we can read isn, sonumReadshould take the minimum between the result ofread4(tempBuf)andn-total. -
At the end, we return
totalas the result of thereadmethod.
Solution
1 | |