C++ C++;二进制读取器和二进制编写器
我需要把一个int数组写成二进制文件作为输出文件,也可以在C++ Linux中读取二进制数据,如二进制代码,如C语言中的BialRead和BinaryWriter。我怎么能这么做C++ C++;二进制读取器和二进制编写器,c++,C++,我需要把一个int数组写成二进制文件作为输出文件,也可以在C++ Linux中读取二进制数据,如二进制代码,如C语言中的BialRead和BinaryWriter。我怎么能这么做 谢谢除非有其他原因,否则您通常会使用std::ostream::write和std::istream::read。由于您正在生成二进制流,因此在打开文件时通常还需要指定std::ios::binary。将int数组转换为(char*),并使用istream::read/ostream::write充实Jerry和J-1
谢谢除非有其他原因,否则您通常会使用
std::ostream::write
和std::istream::read
。由于您正在生成二进制流,因此在打开文件时通常还需要指定std::ios::binary
。将int
数组转换为(char*)
,并使用istream::read
/ostream::write充实Jerry和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);
流文件的std::of(文件名,ios::binary);
myFile.write(static_cast(&x),sizeof x);
...
读取(静态_cast(x),大小x);
另外,如果您需要更多的可移植性,您可能需要考虑将数据放在网络字节顺序中:请参阅系统上NtoHL等的“man”页(或等效项)。
这里有一些有用的代码: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;
}
bool readBinVector(常量std::string&fname,std::vector&val){
长N;
std::fstream in(fname.c_str(),std::ios_base::binary | std::ios_base::in | std::ios::ate);
如果(!in.is_open()){
std::cout以下是一个您可能会发现有用的答案: