`

LeetCode 158 - 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 function int read(char *buf, int n) that reads n characters from the file.

read函数可能被多次调用

[分析]
跟之前的一道题目比,这一题要复杂不少。主要是因为read函数可以调用多次以后,有可能文件中的部分内容被读出来,但是暂时没有用到。因此需要额外的空间来缓存读出来的字符。

[注意事项]
1)对于几个变量的解读:
- buffer 存储从文件中读出来的字符
- offset 上一次读取之后buffer中剩下字符的偏移量
- bufsize buffer中剩下字符的个数

private char[] buffer = new char[4];
private int offset = 0, bufsize = 0; 
public int read(char[] buf, int n) {
    int total = 0;
    boolean eof = false;
    while (!eof && total < n) {
        if (bufsize == 0) {
			bufsize = read4(buffer);
			if (bufsize < 4) {
				eof = true;
			}
		}
        int bytes = Math.min(n - total, bufsize); 
        System.arraycopy(buffer /*src*/, offset /*srcPos*/, 
                         buf /*dest*/,   total /*destPos*/, 
                         bytes /*length*/);
        offset = (offset + bytes) % 4;
        bufsize -= bytes;
        total += bytes;
    }
    return total;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics