Given API:
int Read4096(char* buf);
It reads data from a file and records the position so that the next time when it is called it read the next 4k chars (or the rest of the file, whichever is smaller) from the file.
The return is the number of chars read.
Todo: Use above API to Implement API
"int Read(char* buf, int n)" which reads any number of chars from the file.
我大概会这么写。
第二种写法是注意到尽量避免内存拷贝。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std; int read4096(char* buf) {
static int count = ;
if (count >= ) {
count -= ;
return ;
} else {
int tmp = count;
count = ;
return tmp;
}
} class Reader {
public:
Reader():remain(), size() {}
int readN(char* buf, int n) {
int readCount = ;
while (readCount < n) {
if (remain >= n - readCount) {
memcpy(buf + readCount, tmp + size - remain, n - readCount);
remain -= (n - readCount);
readCount = n;
} else {
if (remain > ) memcpy(buf, tmp + size - remain, remain);
readCount += remain;
remain = size = read4096(tmp);
if (size == ) break;
}
}
return readCount;
} // should be more efficient, avoid some memory copy
int readN2(char* buf, int n) {
if (remain >= n) {
memcpy(buf, tmp + size - remain, n);
remain -= n;
return n;
}
int readCount = ;
if (remain > ) {
memcpy(buf, tmp + size - remain, remain);
readCount += remain;
remain = ;
}
while (readCount + <= n) {
int count = read4096(buf + readCount);
readCount += count;
if (count < ) {
return readCount;
}
}
if (readCount < n) {
size = read4096(tmp);
if (size >= n - readCount) {
memcpy(buf + readCount, tmp, n - readCount);
remain = size - n + readCount;
readCount = n;
} else {
memcpy(buf + readCount, tmp, size);
readCount += size;
}
}
return readCount;
}
private:
int remain;
int size;
char tmp[];
};
int main(int argc, char** argv) {
freopen("input.txt", "r", stdin);
Reader reader; char buff[];
int n = ;
while (true) {
int count = reader.readN2(buff, n);
cout << n << " " << count << endl;
if (count == ) break;
} return ;
}