Imagine you're working with a file reading system that has a quirky limitation: you can only read the file in chunks of exactly 4 characters at a time using a built-in method called read4. Your task is to implement a more flexible read method that can read any number of characters n from the file.
The Challenge: You need to bridge the gap between the fixed 4-character chunks and the variable-length reads that users want.
How read4 works:
- It reads up to 4 consecutive characters from the file
- Stores them in a buffer array
buf4 - Returns the actual number of characters read (could be less than 4 at end of file)
- Maintains its own file pointer that advances automatically
Your Goal: Implement read(buf, n) that reads exactly n characters (or fewer if end of file is reached) and stores them in the destination buffer buf.
Example: If the file contains "abcdefgh" and you want to read 6 characters, your method should return 6 and fill buf with "abcdef".
Input & Output
Constraints
- 0 โค n โค 108
- The file contains at most 108 characters
- read4 is guaranteed to work correctly and read up to 4 characters
- You cannot manipulate the file directly - only through read4
- The read function will only be called once per test case