C++ Solution - 7 Lines - Kind of Socket Reading Problem


  • 3
    S

    I agree with most that the question is ambiguous to an extent. However if you have ever come across socket programming this might not be new to you. Where you pass a header frame requesting how many bytes you want to read and then on receiving that frame you process reading those bytes.

    My Solution:

    int read(char *buf, int n) {
    	if (n <= 0) return n;
    	int bytes = 0, totalBytes = 0;
    	while (true) {
    		bytes = read4(buf + totalBytes);
    		totalBytes += bytes;
    		if (bytes == 0) return totalBytes; // end of file
    		if (totalBytes >= n) return n; // we have read what we were expected to read
    	}
    }

  • 0
    Y

    If n (max size of buf) is less than 4 and the file has 4 or more bytes, wouldn't the call to read4() result in buffer overflow? I think you need to take that into consideration as well.


  • 0
    S

    You are right. From the statement I believe it is assured that the buffer will have enough storage for at least 4 bytes or "that reads n characters from the file." enough storage for n bytes.


Log in to reply
 

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