我需要写一个int数组作为二进制输出文件,也读取二进制数据在C++ Linux程序中的int,就像C#中的BinaryReader和BinaryWriter一样。我怎么能这样做?C++ BinaryReader和BinaryWriter
感谢
我需要写一个int数组作为二进制输出文件,也读取二进制数据在C++ Linux程序中的int,就像C#中的BinaryReader和BinaryWriter一样。我怎么能这样做?C++ BinaryReader和BinaryWriter
感谢
除非一些优秀的理由不这样做,你通常使用std::ostream::write
和std::istream::read
。由于您正在生成二进制流,因此在打开文件时通常还需要指定std::ios::binary
。
将int
排列为(char*)
并使用istream::read
/ostream::write
?
只是为了充实杰里和J-16 SDiZ的建议:
std::ofstream file(filename, ios::binary);
myFile.write (static_cast<const char*>(&x), sizeof x);
...
file.read(static_cast<char *>(x), sizeof x);
此外,你可能想,如果你需要更多的便携性考虑将数据在网络字节顺序:请参见手册页(或等效)ntohl等在您的系统上。
这里是一些代码,你可能会发现有用:
bool readBinVector(const std::string &fname, std::vector<double> &val) {
long N;
std::fstream in(fname.c_str(), std::ios_base::binary | std::ios_base::in | std::ios::ate);
if(!in.is_open()) {
std::cout << "Error opening the file\n" << fname << "\n" << std::endl;
return false;
}
N = in.tellg()/(8);
val.resize(N);
in.seekg(0,std::ios::beg); // begeinning of file
in.read((char*)&val[0], N*sizeof(double));
in.close();
return true;
}
bool writeBinVector(const std::string &fname, const std::vector<double> &val) {
std::ofstream outfile (fname.c_str(),std::ofstream::binary);
outfile.write((char*)&val[0],val.size()*8);
outfile.close();
return true;
}
这里,你可能会发现有用的答案: http://stackoverflow.com/questions/14077781/id-like-to-use- ifstream的和 - ofstream的功能于C到模拟-CS-BinaryReader在二进制 – KBog 2012-12-29 01:19:45