我正在尝试以二进制格式写入文件。我有以下代码,但它以文本格式保存文件。

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    std::string ref = "Ecoli. 123";
    unsigned int size = 124;

    std::ofstream supp_info_output("binary_file",  std::ios::out | std::ios::binary); // saving file
    supp_info_output << ref << std::endl;
    supp_info_output << size << std::endl;
    supp_info_output.close();

    std::ifstream supp_info_input("binary_file", std::ios::in | std::ios::binary); // loading file
    std::string supp_info_line;
    while( std::getline( supp_info_input, supp_info_line ).good() ){
        std::cout << supp_info_line << std::endl;
    }
    supp_info_input.close();
}

在代码中,我正在写入一些数据,然后再次读取数据。读写没有问题,但我需要二进制格式的文件。

最佳答案

使用 ofstream::write 写入二进制数据,使用 ifstream::read 读取它们。请注意,您应该保存字符串的长度,因为您应该知道要进一步读取多少字节。

std::string ref = "Ecoli. 123";
unsigned int size = 124;

std::ofstream supp_info_output("binary_file",  std::ios::out | std::ios::binary); // saving file
unsigned int stringLength = ref.length();
supp_info_output.write( (char*)( &stringLength ), sizeof( stringLength ) );
supp_info_output.write( ref.c_str(), ref.length() );
supp_info_output.write( (char*)( &size ), sizeof( size ) );
supp_info_output.close();

以下是阅读方法:
std::string ref;
unsigned int size;

std::ifstream supp_info_input("binary_file", std::ios::in | std::ios::binary); // loading file
unsigned int stringLength;
supp_info_input.read( (char*)( &stringLength ), sizeof( stringLength ) );
ref.resize( stringLength );
supp_info_input.read( (char*)ref.c_str(), stringLength );
supp_info_input.read( (char*)( &size ), sizeof( size ) );
supp_info_input.close();

关于c++ - 以二进制格式写入文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43602649/

10-09 06:22
查看更多