7 Lines - C++ 0ms


  • 0
    J
    int read(char *buf, int n) {
        int ans = 0, cur_char_read = 0;
        
        while(n > 0 && (cur_char_read = read4(buf)) > 0) {
            ans += min(n, cur_char_read);
            n -= cur_char_read;
            buf += cur_char_read;
        }
        
        return ans;
    }

  • 0
    H

    This answer is not 100% correct in the sense that it may cause overwrite in buf. Consider the situation that the file has 8 chars but the read is called with n=3. In this case, we should never call read4() on buf directly because that will overwrite 1 byte after the allocated space of buf, which has only 3 . The correct way to handle this is to read into a temporary buffer when there is risk for buf overwrite.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.