爱小动物的人就是不冷!# pets - 心有所宠
y*e
1 楼
题意我有点迷糊,不明白为啥public int read(char[] buf, int n)给出说buf是
destination buffer,
但看了答案之后半懂不懂的写了一个c++的,通过了,是这样的
int read(char *buf, int n) {
bool eof=false;
int readBytes=0;
while(!eof && readBytes<=n)
{
int sz=read4(buf);
if(sz<4) eof=true;
int bytes = min(n - readBytes, sz);
readBytes+=bytes;
buf+=bytes;
}
return readBytes;
}
大概的思路就是每次用read4从buf里读,然后指针往后挪,一直挪到eof或者n reached
,这里的buf应该和我理解的一样就是要读的source file。
但java的答案我就很糊涂了,因为没有那个可以一直指向char array头的指针,于是有
了一个char array叫buffer
public int read(char[] buf, int n) {
char[] buffer = new char[4];
int readBytes = 0;
boolean eof = false;
while(!eof && readBytes < n){
int sz = read4(buffer);
if(sz < 4){
eof = true;
}
int bytes = Math.min(n - readBytes, sz);
System.arraycopy(buffer, 0, buf, readBytes, bytes);
readBytes += bytes;
}
return readBytes;
}
我的问题是这个buffer怎么从buf里copy数据的? 不是应该从buf里拷贝到buffer,一次
烤4个char,为啥source和dest我理解错了?一开始的时候我们initialize一个空的
buffer,为啥int sz = read4(buffer)就能populate buffer?如果说buffer不是
source而是destination,那source file又是哪个?
头疼!心塞!
destination buffer,
但看了答案之后半懂不懂的写了一个c++的,通过了,是这样的
int read(char *buf, int n) {
bool eof=false;
int readBytes=0;
while(!eof && readBytes<=n)
{
int sz=read4(buf);
if(sz<4) eof=true;
int bytes = min(n - readBytes, sz);
readBytes+=bytes;
buf+=bytes;
}
return readBytes;
}
大概的思路就是每次用read4从buf里读,然后指针往后挪,一直挪到eof或者n reached
,这里的buf应该和我理解的一样就是要读的source file。
但java的答案我就很糊涂了,因为没有那个可以一直指向char array头的指针,于是有
了一个char array叫buffer
public int read(char[] buf, int n) {
char[] buffer = new char[4];
int readBytes = 0;
boolean eof = false;
while(!eof && readBytes < n){
int sz = read4(buffer);
if(sz < 4){
eof = true;
}
int bytes = Math.min(n - readBytes, sz);
System.arraycopy(buffer, 0, buf, readBytes, bytes);
readBytes += bytes;
}
return readBytes;
}
我的问题是这个buffer怎么从buf里copy数据的? 不是应该从buf里拷贝到buffer,一次
烤4个char,为啥source和dest我理解错了?一开始的时候我们initialize一个空的
buffer,为啥int sz = read4(buffer)就能populate buffer?如果说buffer不是
source而是destination,那source file又是哪个?
头疼!心塞!