Read4096
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.
我大概会这么写。
第二种写法是注意到尽量避免内存拷贝。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 int read4096(char* buf) { 7 static int count = 9999; 8 if (count >= 4096) { 9 count -= 4096; 10 return 4096; 11 } else { 12 int tmp = count; 13 count = 0; 14 return tmp; 15 } 16 } 17 18 class Reader { 19 public: 20 Reader():remain(0), size(0) {} 21 int readN(char* buf, int n) { 22 int readCount = 0; 23 while (readCount < n) { 24 if (remain >= n - readCount) { 25 memcpy(buf + readCount, tmp + size - remain, n - readCount); 26 remain -= (n - readCount); 27 readCount = n; 28 } else { 29 if (remain > 0) memcpy(buf, tmp + size - remain, remain); 30 readCount += remain; 31 remain = size = read4096(tmp); 32 if (size == 0) break; 33 } 34 } 35 return readCount; 36 } 37 38 // should be more efficient, avoid some memory copy 39 int readN2(char* buf, int n) { 40 if (remain >= n) { 41 memcpy(buf, tmp + size - remain, n); 42 remain -= n; 43 return n; 44 } 45 int readCount = 0; 46 if (remain > 0) { 47 memcpy(buf, tmp + size - remain, remain); 48 readCount += remain; 49 remain = 0; 50 } 51 while (readCount + 4096 <= n) { 52 int count = read4096(buf + readCount); 53 readCount += count; 54 if (count < 4096) { 55 return readCount; 56 } 57 } 58 if (readCount < n) { 59 size = read4096(tmp); 60 if (size >= n - readCount) { 61 memcpy(buf + readCount, tmp, n - readCount); 62 remain = size - n + readCount; 63 readCount = n; 64 } else { 65 memcpy(buf + readCount, tmp, size); 66 readCount += size; 67 } 68 } 69 return readCount; 70 } 71 private: 72 int remain; 73 int size; 74 char tmp[4096]; 75 }; 76 int main(int argc, char** argv) { 77 freopen("input.txt", "r", stdin); 78 Reader reader; 79 80 char buff[4096]; 81 int n = 1024; 82 while (true) { 83 int count = reader.readN2(buff, n); 84 cout << n << " " << count << endl; 85 if (count == 0) break; 86 } 87 88 return 0; 89 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步