zoukankan      html  css  js  c++  java
  • Read N Characters Given Read4 II

    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.

    Note:
    The read function may be called multiple times.

     1 /* The read4 API is defined in the parent class Reader4.
     2       int read4(char[] buf); */
     3 
     4 public class Solution extends Reader4 {
     5     /**
     6      * @param buf Destination buffer
     7      * @param n   Maximum number of characters to read
     8      * @return    The number of characters read
     9      */
    10     private char[] tmp = new char[4];
    11     private int tmpPoint; //indicate which position we should start reading
    12     private int tmpContain;//indicate how many char in the tmp buff
    13     public int read(char[] buf, int n) {
    14         int cur = 0;
    15         while(cur < n){
    16             if(tmpPoint == 0){
    17                 tmpContain = read4(tmp);
    18             }
    19             if(tmpContain == 0){
    20                 return cur;
    21             }
    22             while(cur < n && tmpPoint < tmpContain){
    23                 buf[cur ++] = tmp[tmpPoint ++];
    24             }
    25             tmpPoint = tmpPoint % tmpContain;
    26         }
    27         return cur;
    28     }
    29 }
  • 相关阅读:
    Common ThreadView
    经典代码IOCP的C#实现(转)
    Common.UdpLib
    Common.TcpLibTcpServerWIOCP
    Common.TcpLibTcpServerY
    sql中将分隔字符串转为临时表的方法
    病毒及流氓软件自我复制的简单实现
    一句sql搞定个人所得税计算
    财务月度的创建及生成
    box2d 教程
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4433877.html
Copyright © 2011-2022 走看看