Read N Characters Given Read4
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 functionint read(char *buf, int n)
that reads n characters from the file.Note:
Theread
function will only be called once for each test case.
3 cases:
file is smaller than n,
file is larger than or equal to n.
// Forward declaration of the read4 API. // malloc in read4 function? int read4(char *buf); class Solution { public: /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ int read(char *buf, int n) { char * p = buf; while(n > 0){ int num = read4(p); if(num == 0) break; // EOF if(n < num){ // read more than needed // may overflow. p = p + n; break; } else{ n -= num; p = p + num; } } return p - buf; } };
Read N Characters Given Read4 II – Call multiple times
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 functionint read(char *buf, int n)
that reads n characters from the file.Note:
Theread
function may be called multiple times.
Use a circle buffer to store the overread characters.
Be aware of variable name shadows!
// Forward declaration of the read4 API. int read4(char *buf); class Solution { public: /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ char buffer[3]; // this name should not be the same as buf, cause it will be shadowed by the parameter of read. int size = 0; // not needed actually. int front = 0; int back = 0; int read(char *buf, int n) { char * p = buf; int i = 0; // fetch buffer while(n > 0 && size > 0){ *p = buffer[front++ % 3]; // may overflow size--; n--; p++; } while(n > 0){ int num = read4(p); if(num == 0) break; // store exceeded chars to buffer if(num > n){ while(n--){ num--; p++; } // p moves to the first exceeded char i = 0; while(i < num){ buffer[back++ % 3] = *(p+i); size++; i++; } break; } else{ p = p + num; n = n - num; } } return p - buf; } };