急!c++如何从文件中读取二进制形式存储的数字?

2024-12-12 20:31:01
推荐回答(3个)
回答1:

//楼主,你只是忘记关闭了,你的程序不用大改的。
#include
#include
using namespace std;
int main()
{
short i=256;

ifstream in_stream;
ofstream out_stream;
out_stream.open("tmp.txt", ios::binary);
//以二进制形式写入i
out_stream.write((char *)&i,sizeof(i));
out_stream.close();
in_stream.open("tmp.txt", ios::binary);
short k;
//读取k
in_stream.read((char*)&k,sizeof(k));
cout<in_stream.close();
return 0;
}

回答2:

#include
#include
using namespace std;
int main()
{
short i=255;

fstream io_stream;
io_stream.open("tmp.txt", ios::binary|ios::out);
//以二进制形式写入i
io_stream.write((char *)&i,sizeof(i));
io_stream.close();
io_stream.open("tmp.txt", ios::binary|ios::in);
short k;
//读取k
io_stream.read((char*)&k,sizeof(k));
cout<io_stream.close();
return 0;
}

回答3:

这样写
#include
#include
#include
int main()
{
short i=256;
char tmp[2];

ifstream in_stream;
ofstream out_stream;
out_stream.open("tmp.txt", ios::binary);
//以二进制形式写入i
memcpy(tmp,&i,sizeof(i));
out_stream.write(tmp,sizeof(i));
in_stream.open("tmp.txt", ios::binary);
short k;
//读取k
in_stream.read(tmp,sizeof(k));
memcpy(&k,tmp,sizeof(k));
cout<}