首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

帮小弟我看看代码:文件读的不正确了。多谢

2012-02-19 
帮我看看代码:文件读的不正确了。。谢谢constintBUFFERSIZE128bytebuffer[BUFFERSIZE]ifstreamifileofst

帮我看看代码:文件读的不正确了。。谢谢
const   int   BUFFERSIZE=128;

byte   buffer[BUFFERSIZE];
ifstream   ifile;
ofstream   ofile;
ofile.open(decFilename);
ifile.open(srcFilename);
ifile.seekg(0,ios::end);
int   fillen=ifile.tellg();
int   times=fillen/BUFFERSIZE;
int   mod=fillen%BUFFERSIZE;
cout < < "fillen=   " < <fillen < <endl;   //   文件长度
cout < < "times=   " < <times < <endl;   //   足够一块的次数
cout < < "mod=   " < <mod < <endl;   //   最后不足一块
for   (int   i=0;i <times;i++)
{
ifile.read((char*)buffer,BUFFERSIZE);
//   <test>   cout < <buffer < <endl;   </test>
ofile.write((char*)buffer,BUFFERSIZE);
}
ifile.read((char*)buffer,mod);
ofile.write((char*)buffer,mod);
ifile.close();
ofile.close();

上面是我的一个程序的片断,这个是复制文件的操作。但是我读文件出来不对啊,中间有个// <test> </test> 是测试用的,你可以看看。我用来度二进制文件的。
谢谢

[解决办法]
ifile.open(srcFilename, ios::in | ios::binary);
ofile.open(decFilename, ios::out | ios::binary);
然后,由于你使用了ifile.seekg(0,ios::end);来获得文件大小,这时文件指针指向文件尾部,
而你在读取前并没有将它指向文件数据开始出,当然读不出。

在for循环前加上:ifile.seekg(0, ios::beg);

热点排行