美文网首页
157. Read N Characters Given Rea

157. Read N Characters Given Rea

作者: larrymusk | 来源:发表于2017-11-25 22:02 被阅读0次

在一个循环内依次调用read4读取四个字符,然后拷贝到buff中,拷贝的时候需要判断是否已经读取的数字大于N,如果只大于N,而且还可以继续从文件读取4个字符,就继续读取,但是不拷贝到buff里面,知道读完文件为止:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        if(n == 0)  
            return 0;  
        int read = 0;  
        char* buffer4 = new char[4];  
        while(true)  
        {  
            int r = read4(buffer4);  
            for(int i = 0;i<r && read<n;i++)  
            {  
                buf[read++]= buffer4[i];  
            }  
            if(r <4 )  
                break;  
        }  
        return read;  
    }
};

相关文章

网友评论

      本文标题:157. Read N Characters Given Rea

      本文链接:https://www.haomeiwen.com/subject/ggkhbxtx.html