C++ Solution - Followup from the easy problem

  • 5

    This is a followup solution from my easy solution here: https://leetcode.com/discuss/98349/c-solution-7-lines-kind-of-socket-reading-problem - The idea is having a local buffer of size 4 which we can read. The first loop checks if we have any data available which was left over from the previous call to read. the %4 operator just mimics a circular buffer. The second loop simply keeps reading until we hit the end of file which is bytes == 0 or we are done reading till n.

         * @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 n; int i = 0;
        	while (available > 0 && i < n) {
        		buf[i++] = store[curp++%4]; --available; // If we have some data left lets read that
        	int bytes = 0;
        	while (true)
        		if (i >= n) return i;
        		bytes = read4(store);
        		if (bytes == 0) return i;
        		while (bytes && i < n) { // populate our buffer given we have bytes to read
        			buf[i++] = store[curp++%4]; --bytes; 
        		available = bytes; // set the remaining bytes - we might need them in next read call
        int available = 0, curp = 0;
        char store[4];

Log in to reply

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