问一问有关于文件操作

ibmc490365333 2012-03-28 09:39:19
这是一个逐字节比较俩文件差异的C++程序,但是最后一行的输出总是不正确。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
unsigned char a,b;
ifstream file1,file2;
file1.open("1",ifstream::binary);
file2.open("2",ifstream::binary);
while(!file1.eof()&&!file2.eof())
{
file1>>a;
file2>>b;
if(a!=b)
cout<<"location:"<<hex<<showbase<<static_cast<int>(file1.tellg())-1<<":file1="<<static_cast<int>(a)<<" "<<"file2="<<static_cast<int>(b)<<endl;
}
file1.close();
file2.close();
return 0;
}

请问这个程序究竟哪里错了。编译环境是Fedora 16,内核为3.3.0-4.fc16.i686.PAE,编译器是gcc (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2)
...全文
74 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Kaile 2012-03-29
  • 打赏
  • 举报
回复
应该正确的最后一行是什么
ibmc490365333 2012-03-29
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]

不要用unsigned char,用char试试
[/Quote]
没用。。。

改成这样都还有问题

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a,b;
ifstream file1,file2;
file1.open("1",ifstream::binary);
file2.open("2",ifstream::binary);
while(!file1.eof()&&!file2.eof())
{
a=file1.get();
b=file2.get();
if(a!=b)
cout<<"location:"<<hex<<showbase<<static_cast<int>(file1.tellg())-1<<":file1="<<a<<" "<<"file2="<<b<<endl;
}
file1.close();
file2.close();
return 0;
}

oniisama 2012-03-29
  • 打赏
  • 举报
回复
不要用unsigned char,用char试试
ibmc490365333 2012-03-29
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

既然用二进制打开,就不要用输入输出符,用get或者read试试
[/Quote]

我也想,但是直接无法编译。。。。file1.get(a);这样gcc会说重载函数调用没有匹配。。。。

最关键的问题是,C++ Perimer 4th的附录A里面说file1.get(a)是可以的。。。。。
ibmc490365333 2012-03-29
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

什么样子的错误?本人在windows下用VS 2005编译器可以,没问题
[/Quote]

不是编译错误,是运行结果不正确。最后一行输出结果不正确
oniisama 2012-03-29
  • 打赏
  • 举报
回复
既然用二进制打开,就不要用输入输出符,用get或者read试试
面包大师 2012-03-29
  • 打赏
  • 举报
回复
什么样子的错误?本人在windows下用VS 2005编译器可以,没问题
ibmc490365333 2012-03-29
  • 打赏
  • 举报
回复
怎么一个人都没有?

64,631

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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