C++标准程序库的输入输出流(I/O Stream)复制文件(4种方法)

使用C++标准程序库的输入输出流(I/O   Stream)复制文件,存在许多的方法,

方法一:逐个字符复制
#include   <   fstream   >

std::ifstream   input( "in ",ios::binary);
std::ofstream   output( "out ",ios::binary);
char   ch;

while   (input.get(ch))   output   < <   ch;

注意:如果使用input> > ch读取字符,则必须先调用input.unsetf(ios::skipws)取消输入流默认的跳过空白符的输入格式,因为换行符是空白符的一种。

方法二:逐行复制

#include   <   fstream   >
#include   <   string   >

std::ifstream   input( "in ",ios::binary);
std::ofstream   output( "out ",ios::binary);
std::string   line;

while   (getline(input,line))   output   < <   line   < <   "\n ";

注意:这里的代码有一个小小的缺陷,如果文件不是纯文本格式的文件,或者文本文件的最后没有换行符,那么会导致复制后的文件末尾添加了一个多余的换行符。

方法三:迭代器复制

#include   <   fstream   >
#include   <   iterator   >
#include   <   algorithm   >

std::ifstream   input( "in ",ios::binary);
std::ofstream   output( "out ",ios::binary);
input.unsetf(ios::skipws);

copy(istream_iterator(input),istream_iterator(),ostream_iterator(output, " "));

同样这里也有一个小技巧,输入流的格式默认为跳过空白字符,因此调用unsetf取消这个格式,才可保证正确的复制。

方法四:缓冲区复制

#include   <   fstream   >

std::ifstream   input( "in ",ios::binary);
std::ofstream   output( "out ",ios::binary);

output   < <   input.rdbuf();

这里直接使用了输入流的缓冲区,因此没有引入额外的临时对象。

很显然,上述四种方法中,最后一种方法最简洁,由于直接操作输入流的缓冲区,从运行效率上来说,也比其他方法有着略微的优势(当然,由于操作系统可能提供了额外的基于设备的文件缓冲机制,也许你无法证实这一点)。因此,除非要对输入内容进行处理,直接复制文件推荐最后一种方法,既不容易出错,又能获得良好的性能。

http://blog.csdn.net/kl222/article/details/7431980

posted @ 2015-12-29 23:03  findumars  Views(1840)  Comments(0Edit  收藏  举报