大佬教程收集整理的这篇文章主要介绍了c – ofstream :: operator <<(streambuf)是一种复制文件的慢速方法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
char buffer[LEN]; ifstream src(srcFile,ios::in | ios::binary); ofstream dest(destFile,ios::out | ios::binary); while (!src.eof()) { src.read(buffer,LEN); dest.write(buffer,src.gcount()); }
这很好用,我确切知道它在做什么.
然后我在stackoverflow上发现了一个帖子(抱歉,现在找不到链接),说我可以用以下代码替换所有上面的代码:
dest << src.rdbuf();
这是好的和紧凑的,但隐藏了很多关于它正在做的事情.事实证明它非常慢,因为ofstream :: operator<<(streambuf)的实现一次移动1个字符(使用snetxc()/ sputc()). 我有办法让这种方法更快吗?我原来的方法有缺点吗? 更新:在Windows上使用运算符<<(streambuf)效率低下. .read()/.write()循环看起来总是比运算符<<更好. 此外,在上面的代码中更改缓冲区的大小不会影响对硬盘驱动器的读写大小.为此,您需要使用stream.rdbuf() – > pubsetbuf()设置缓冲区.
对我的系统进行快速测试,如果我将LEN设置为0(因此无缓冲),则需要10秒才能复制1 MB文件.使用4k缓冲区,它在不到一秒钟内完成.
#include <iostream> #include <fstream> int main() { using namespace std; const char* srcFile = "test.in"; const char* destFile = "test.out"; ifstream src; ofstream dest; const int LEN=8192; char buffer_out[LEN]; char buffer_in[LEN]; if (LEN) { src.rdbuf()->pubsetbuf(buffer_in,LEN ); dest.rdbuf()->pubsetbuf(buffer_out,LEN); } else { src.rdbuf()->pubsetbuf(NULL,0 ); dest.rdbuf()->pubsetbuf(NULL,0); } src.open(srcFile,ios::in | ios::binary); dest.open(destFile,ios::out | ios::binary); dest << src.rdbuf(); }
以上是大佬教程为你收集整理的c – ofstream :: operator <<(streambuf)是一种复制文件的慢速方法全部内容,希望文章能够帮你解决c – ofstream :: operator <<(streambuf)是一种复制文件的慢速方法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。