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; }
相关推荐
大佬的leetcode刷题笔记(c++版本)
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
LeetCode题解 - Java语言实现-181页.pdf
leetcode 答案Leetcode---数据库 我对 Leetcode 数据库问题的回答
leetcode1-300.docx
彩色版本 正版 pdf 精讲数据结构 + 算法 链表 树 图表 贪心算法 指针 动态规划 查找算法
Algorithm-LeetCode-Sol-Res.zip,干净,易懂的解决方案和资源,为leetcode在线判断算法问题。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
leetcode 答案leetcode--python Leetcode 的答案
leetcode-cli 注意:这个存储库是为了临时使用而分叉的。 注意:从 webbrowser 复制 cookie 并使用leetcode user -c可以临时修复不能。 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的...
500195422331430LeetCode题解 - Java语言实现.zip
leetcode 答案LeetCode--哈希表 以上是我对“哈希表”问题的回答,都被leetcode的判断所接受。
leetcode 答案解析 golang解答
本书包含了 LeetCode Online Judge所有题目的答案,所有代码经过精心编写,编码规范良好,适合读者反复揣摩,模仿,甚至在纸上默写
leetcode1-240题中文题解,md格式,java版本 有题目有题解有代码 需要使用markdown打开
leetcode 1 -200题所有源码 有问题私聊我
leetcode-cli 一个享受 leetcode 的高效 cli 工具! 非常感谢 leetcode.com,一个非常棒的网站! ⦙⦙⦙⦙⦙⦙⦙⦙ 一个很打问题的方法。 问题来缓解离线思考。 编码前的源代码。 居住和与 leetcode.com。 下载你...