LeetCode – Refresh – Read N Characters Given Read4

本文介绍了一种通过循环调用read4函数来高效读取文件的方法,并实现了对目标缓冲区buf的最大读取长度控制。当读取长度超过指定长度时,会进行特殊处理确保字符串正确终止。

Read the buffer from file every time. After loop terminated, check whether the total lens is over 4.

Then use n - len (a negative number) to set the end char.

 

 1 // Forward declaration of the read4 API.
 2 int read4(char *buf);
 3 
 4 class Solution {
 5 public:
 6     /**
 7      * @param buf Destination buffer
 8      * @param n   Maximum number of characters to read
 9      * @return    The number of characters read
10      */
11     int read(char *buf, int n) {
12         int len = 0, each = INT_MAX;
13         while (len < n && (each = read4(buf))) {
14             len += each;
15             buf += each;
16         }
17         if (len >= n) {
18             buf[n-len] = '\0';
19             len = n;
20         }
21         return len;
22     }
23 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4357397.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值