Read Buffer II

来源:互联网 发布:秉钧网络 编辑:程序博客网 时间:2024/06/03 08:59
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 function int read(char *buf, int n) that reads n characters from the file.

I dont very understand the above statement first. So, it is better to make an example:

Suppose we want to implement read5 and currently we have 11 chars length file to read. If we use read4 and read5 can be called multiple times, the first time read5 will read 5 characters but it will call read4 twice and read over 3 characters. Thus, we need a way to pre-save the extra 3 characters and leave it for the next time read5 function was called. 

So, to do that, we use a 4 size buffer to store the read4 function. 

buffer : (buff1, buff2, buff3, buff4), and we use offset to point to last time's end pos and buffsize  to stand for left overs.

So, offset = 0, buffsize = 0; we want to realize read5 function.

1: first check last time's leftover, if has leftover, dont call read4. int sz = buffsize > 0 ? buffsize, read4.

2: check whether the left over is enough for our current read. int len = min(n-readedSize, sz) // this is the actually size we want to read.

3: copy then into read5's buffer. system.arraycopy(sourcebuffer, sourceindex, targetbuf, targetpos, readlength), in our function, it will be

    system.arraycopy(buffer, offset, buf, readedsize, len);

4: now we need to recalculate the offset and leftover size to prepare for the next call. offset = (offset + len) % 4, leftover = sz - len;

    and the accumulated size we have read right now are: readedSize += len.

5: However, in this process, we omit a very important problem. We will read the EOF (end of file). That is to say, the length of file is not multiple of read5. Thus, we need to set a flag: eof = false. Once there is no leftover in our pre-save buffer and the new read4 can read less than 4 characters, we reach the end of file now!


Thus, the whole process is as follows:

char* buffer = char buff[4];int offset = 0;int buffsize = 0;int read(char* buff, int n) {  int readbuf = 0;  while(!eof && readbuf < n) {    int sz = buffsize > 0 ? bufsize : read4; // if there are still leftovers, read the leftovers first.    if(offset == 0 && sz < 4) eof = true;   // if we reach the end of file.    int len = min(n - readbuf, sz);         // the actual len we want to read.    system.arraycopy(buff, offset, buff, readbuff, len); // copy the leftovers of len from source to target.    readbuf += len;    // calculate the new offset, new leftover size, increase the already read size.    offset = (offset + len) % 4;    buffsize = sz - len;  }}

 



0 0
原创粉丝点击