主题:二进制文件输出问题。。。
iebboy
[专家分:0] 发布于 2011-05-26 11:19:00
#include <iostream.h>
#include <string.h>
#include <fstream.h>
void main()
{
ifstream infile;
ofstream outfile;
float abc;
double d=1.43;
outfile.open("abc.bin",ios::binary);
outfile<<d;
outfile.close();
infile.open("abc.bin",ios::binary);
infile>>abc;
cout<<abc;
}
为什么生成的abc.bin文件是4字节,d不是double型。
回复列表 (共4个回复)
沙发
bruceteen [专家分:42660] 发布于 2011-05-26 14:39:00
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile( "abc.bin", ios::binary );
double a = 1.43;
outfile.write( (const char*)&a, sizeof(a) );
outfile.close();
ifstream infile( "abc.bin", ios::binary );
double b;
infile.read( (char*)&b, sizeof(b) );
infile.close();
cout << b;
return 0;
}
板凳
cgl_lgs [专家分:21040] 发布于 2011-05-26 21:49:00
个人认为操作文件很多时候stream没有FILE*来得舒服~~~~~
3 楼
qimishan [专家分:30] 发布于 2011-05-26 21:58:00
因为你用的二进制方式读写文件的呀
4 楼
cxxcomp [专家分:2370] 发布于 2011-05-26 22:12:00
bruceteen给出了一个方法,我做个解释。首先,如果对于LZ的
double d;
ofstream outfile;
float abc;
double d=1.43;
outfile.open("abc.bin",ios::binary);
outfile<<d; .......
的方法输出二进制形式的话,是不正确的。即时你使用了ios::binary,也是枉然,流一样会把double转为字符形式。如果你用editplus看这个文件结构的话。会看的很清楚。所以,如果你想输出二进制,那么必须把内存中的二进制一模一样的按字节写入文件。所以,bruceteen代码里会出现ofstream::write, ifsteam::read函数。如果你不想采用直接调用成员函数的方法,而还是习惯用<<的样子的话,我再给段码。把read,write封装起来就行了。
///////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
class bofstream : public ofstream
{
public:
bofstream(const char* outfile)
: ofstream(outfile, ios::out|binary) {};
~bofstream() {};
bofstream& operator<<(double d)
{
WriteByte(&d, sizeof(d));
return *this;
}
protected:
virtual void WriteByte(const void* p, int nLen);
private:
};
inline void bofstream::WriteByte(const void* p, int nLen)
{
if (!p && nLen<=0) return ;
write((char*)p, nLen);
}
int main(int ac, char **av, char **ev)
{
bofstream bofs("TEST.D");
if (!bofs)
{
std::cerr << "unable to write to TEST.D\n";
exit(EXIT_FAILURE);
}
double d = 3.1415926;
bofs << d;
bofs << d * d;
double dd = 3.2E-8;
bofs << dd;
#ifdef _DEBUG
system("pause");
#endif
return EXIT_SUCCESS;
}
run后,你看看TEST.D的字节是多大?3 * 8 == 24(byte)
我来回复