157. Read N Characters Given Read4

本文介绍了一种利用read4 API实现read函数的方法,通过维护一个临时缓存区来连续读取文件并返回指定数量的字符。该方法适用于多次调用read函数时保持数据的连续性和一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

用一个临时数组buffer存每次读完的数据,start表示offset应该从global read数组里哪里开始写。每次读完了放进buffer,再写进read里面。最后记录一下count,如果count<4证明读完文件了不用再读了。

// use pointer start to indicate the current filling position in global char array read[].
// use a char array buffer[] of length 4 as an intermediate container for new characters just read, and later output these character to global char array read[]

    public int read(char[] read, int n) {
        char[] buffer = new char[4];
        int start = 0;
        while (start <= n - 1) {
            int count = read4(buffer);
            for (int i = 0; i < count && start <= n - 1; i++) {
                read[start++] = buffer[i];
            }
            if (count < 4) {
                break;
            }
        }
        return start;
    }
比如先call了n=3,然后call n=5,那么第一次就读入了4个char,第二次call应该把上一次的最后一个char拿来。也就是说要有个cache取缓存已读取的字符,然后从这个cache里面取。


/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    private int buffPtr = 0;
    private int buffCnt = 0;
    private char[] buff = new char[4];
    public int read(char[] buf, int n) {
        int ptr = 0;
        while (ptr < n) {
            if (buffPtr == 0) {
                buffCnt = read4(buff);
            }
            if (buffCnt == 0) break;
            while (ptr < n && buffPtr < buffCnt) {
                buf[ptr++] = buff[buffPtr++];
            }
            if (buffPtr >= buffCnt) buffPtr = 0;
        }
        return ptr;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值