c++文件复制 每次复制的字节数不同结果不同
把一个文件复制到另一个文件,每次复制的字节数由自己指定(输入n),
输出源文件的全部字节数,以及第一次需要复制的字节数,和最后一次复制的内容(用来判断是符复制完全),
代码如下:
#include<fstream>
#include<iostream>
using namespace std;
void main()
{
int n(1);
char buff[1024];
strset(buff,'\0');
long bytes;
strset(buff,'\0');
fstream infile,outfile;
infile.open("E:\\3eee\\suns\\11_41.txt",ios::in);
outfile.open("E:\\3eee\\suns\\11_42.txt",ios::out|ios::trunc);
infile.seekg(0,ios::end);
bytes = infile.tellg();//计算从头到尾有多少个字节
infile.seekg(0,ios::beg);
cout<<"bytes:"<<bytes<<endl;
cout<<"cin:n=";
cin>>n;
infile.read(buff,bytes%n);//第一次读余数个
//infile.read(buff,bytes%n+1);//第一次读取n的余数个
cout<<"n:"<<n<<":"<<endl;
cout<<"strlen(buff)"<<strlen(buff);
while(!infile.eof())
{
outfile.write(buff,strlen(buff));
infile.read(buff,n);
}
cout<<"\nbuff:"<<buff<<endl;//最后一次读的内容
infile.close();
outfile.close();
}
问题;当n不同时 结果不同:
我用的是vc++6.0测试结果如下:
n的值:1234567,(89)10(11)12(13)1415(1617) //()中的不能复制完全
如:n==5的结果:(正确)
bytes:8422
cin:n=5
n:5:
strlen(buff)2
buff:***/
Press any key to continue
n==13的结果:(不正确)
bytes:8422
cin:n=13
n:13:
strlen(buff)11
buff:*******/
****
Press any key to continue //很明显没读完
[解决办法]
.
[解决办法]
推荐使用WinHex软件查看文件或内存中的原始字节内容。
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
[解决办法]
坐等标准答案!
[解决办法]
"E:\\3eee\\suns\\11_41.txt"楼主,你的这个文件里面的内容是什么,你自己回复的那个看的我好乱,重新传一个把。