Problem
Given a file and assume that you can only read the file using a given method read4
, implement a method read
to read n characters. Your method read
may be called multiple times.
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 |
|
Note:
- Consider that you cannot manipulate the file directly, the file is only accesible for
read4
but not forread
. - The
read
function may be called multiple times. - Please remember to RESET your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see here for more details.
- You may assume the destination buffer array,
buf
, is guaranteed to have enough space for storingn
characters. - It is guaranteed that in a given test case the same buffer
buf
is called by read.
Explanation
-
The difference between this question and the first version is that the
read()
function will be called multiple times. -
The trouble here will be as the following example if using the first version solution:
1 |
|
-
This is because when you use
read4()
to read, the pointer to read file has already moved toe
after the first call ofread4()
. So it’s not correct any more. -
In order to solve, we need to persist the characters that has been already read by using
read4
but it’s not put into the result ofread()
. -
In the solution below, we are using a
buf4[]
to store the characters read by usingread4
and also abuf4Size
andbuf4Index
to keep track of the size of thebuf4
and the index to use inbuf4[]
.
Solution
1 |
|