C++怎么读写二进制文件
C++如何读写二进制文件
#include <fstream>
#include <iostream>
using namespace std;
void main()
{
char *fileName = "1.dat";
ofstream os(fileName, ofstream::binary);
short b = 128;
os << b ;
ifstream is(fileName, ifstream::binary);
short a;
is >> a;
cout << a << endl;
}
为什么输出是-13108
------解决方案--------------------
需要刷新缓冲区
#include <fstream>
#include <iostream>
using namespace std;
void main()
{
char *fileName = "1.dat";
ofstream os(fileName, ofstream::binary);
short b = 128;
os << b ;
ifstream is(fileName, ifstream::binary);
short a;
is >> a;
cout << a << endl;
}
为什么输出是-13108
------解决方案--------------------
需要刷新缓冲区
- C/C++ code
os << b ; os.flush(); ifstream is(fileName, ifstream::binary); short a; is >> a; cout << a << endl;