有一个read4方法每次只能读4个字符,它有一个buf[]缓存它读的内容。要自己写一个read方法,输出读了多少个字符。
给定一个文件并假定您只能使用给定的方法读取该文件 read4
,请实现一个方法以读取n个字符。
说明read4:
API read4
从文件中读取4个连续字符,然后将这些字符写入缓冲区数组buf
。
返回值是读取的实际字符数。
请注意,它 read4()
具有自己的文件指针,就像FILE *fp
在C语言中一样。
read4的定义:
参数:char [] buf
返回:int
注意:buf []是目标而不是源,来自read4的结果将被复制到buf []
以下是工作方式的高层示例read4
:
File file("abcdefghijk"); // File is "abcdefghijk", initially file pointer (fp) points to 'a'
char[] buf = new char[4]; // Create buffer with enough space to store characters
read4(buf); // read4 returns 4. Now buf = "abcd", fp points to 'e'
read4(buf); // read4 returns 4. Now buf = "efgh", fp points to 'i'
read4(buf); // read4 returns 3. Now buf = "ijk", fp points to end of file
read方法:
通过使用该read4
方法,实现 从文件read
读取n个字符并将其存储在缓冲区array中的方法 buf
。考虑到您不能直接操作该文件。
返回值是读取的实际字符数。
read定义:
参数:char [] buf,int n
返回:int
注意:buf []是目标而不是源,需要将结果写入buf []
Eg.1:
Input: file =“ abc”,n = 4
Output: 3
说明:调用read方法后,buf应该包含“ abc”。我们从文件中总共读取了3个字符,因此返回3。
请注意,“ abc”是文件的内容,而不是buf。buf是您必须将结果写入其中的目标缓冲区。
Eg.2:
Input: file =“ abcde”,n = 5
Output: 5
说明:调用read方法后,buf应该包含“ abcde”。我们从文件中总共读取了5个字符,因此返回5。
Eg.3:
Input: file =“ abcdABCD1234”,n = 12
Output: 12
说明:调用读取方法后,buf应包含“ abcdABCD1234”。我们从文件中总共读取了12个字符,因此返回12。
Eg.4:
Input: file =“ leetcode”,n = 5 Output: 5 说明:调用read方法后,buf应该包含“ leetc”。我们从文件中总共读取了5个字符,因此返回5。 PS:
- 考虑到不能直接操作该文件,该文件仅可用于,
read4
而不能用于read
。 read
对于每个测试用例,该函数仅被调用一次。- 可以假定目标缓冲区数组
buf
保证有足够的空间来存储 n个 字符。
"""
The read4 API is already defined for you.
@param buf, a list of characters
@return an integer
def read4(buf):
# Below is an example of how the read4 API can be called.
file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
buf = [' '] * 4 # Create buffer with enough space to store characters
read4(buf) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
read4(buf) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
read4(buf) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
"""
class Solution:
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
res=0
while n>0:
a=['']*4 #初始化一个list['','','','']
b=read4(a) #用read4读取,并将读取字符的个数赋值给b
for i in range(min(4,n)): #n可能为1~4之间的数
buf[res+i]=a[i] #把a[]中的字符给buf[]
res+=min(n,b)
n-=b
if b<4:
break
return res