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
read4
but not forread
. - The
read
function 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
read4
to implement methodread
. In theread
method, the maximum size we can read isn
, and the read data should store inbuf
, and every read operation, the data inbuf
will refresh. -
First, we create a counter
total
, andchar[4] tempBuf
to store the data usingread4(tempBuf)
, then ifread4
’s return numbernumRead
is not 0, then we loop from 0 tonumRead
exclusive to store the data intempBuf
tobuf[total+i]
. Since the maximum number we can read isn
, sonumRead
should take the minimum between the result ofread4(tempBuf)
andn-total
. -
At the end, we return
total
as the result of theread
method.
Solution
1 |
|