copy文件问题

erwinrommel 2004-07-18 06:10:34
自己写了一个copy文件函数,在copy exe时,(对于同一个文件的拷贝)有时可以完成copy,有时却会相差一点(即无法执行复制后的文件),望达人赐教!~

// 拷贝二进制文件
void copyfile ( char const* sourcefile, char const* destinationfile )
{
ifstream ifile( sourcefile, ios::binary );
if ( !ifile.is_open() )
return;
string str,temstr;
while ( getline ( ifile, temstr ) )
str += (temstr+'\n');
ofstream ofile( destinationfile, ios::binary );
ofile << str;
}
...全文
108 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
abitz 2004-07-20
  • 打赏
  • 举报
回复
getline 断的时候受到平台的影响,有的是'\n', 有的是'\r\n';
=======================================================
这一平台相关特性在以文本模式打开文件时就已经被去掉了。
在windows上以文本模式打开文件时不会读到'\r'。
看一下标准库源码便知。
erwinrommel 2004-07-19
  • 打赏
  • 举报
回复
谢谢你们,结帖,给分!
sharkhuang 2004-07-19
  • 打赏
  • 举报
回复
已经发现问题了.
rorot 2004-07-18
  • 打赏
  • 举报
回复
getline 断的时候受到平台的影响,有的是'\n', 有的是'\r\n';而且把读入的元素放进了char_type[]数组中,可能会改变二进制数据.

而且你上面的程序本身就有问题:

ifstream ifile( sourcefile, ios::binary );
if ( !ifile.good() ) // infile.is_open()不能监测这个文件被重复打开....
return;
string str,temstr;
while ( !ifile.eof() )
str += ifile.get(); // get()是二进制...
ofstream ofile( destinationfile, ios::binary );
ofile << str;
idau7 2004-07-18
  • 打赏
  • 举报
回复
学到了。
abitz 2004-07-18
  • 打赏
  • 举报
回复
你以二进制方式打开文件,却以文本方式对文件进行处理,这比较令人费解。
getline在默认参数下会以widen('\n')作为结束控制来读取文件内容;这种工作方式表明它适于处理文本文件。
当你需要在二进制层面上copy文件时,不应该使用getline。
可以使用适于非格式化处理文件的函数,如getc等。

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧