std::ofstream 和 std::ifstream读写文件
包含头文件:
#include <fstream>
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "Test.b";
{
std::ofstream ostrm(filename, std::ios::binary);
double d = 3.14;
ostrm.write(reinterpret_cast<char*>(&d), sizeof d); // binary output
ostrm << 123 << "abc" << '\n'; // text output
}
// read back
std::ifstream istrm(filename, std::ios::binary);
double d;
istrm.read(reinterpret_cast<char*>(&d), sizeof d);
int n;
std::string s;
istrm >> n >> s;
std::cout << " read back: " << d << ' ' << n << ' ' << s << '\n';
}
运行结果:
生成文件:Test.b
流运算符域宽问题
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "Test.b";
{
std::ofstream ostrm(filename, std::ios::out);
double d = 3.1415926;
float f = 56839.12905;
ostrm << d << ", " << f << '\n'; // text output
}
}
浮点型和双精度型默认输出有效位是 6位