以二进制格式写入文件 [英] Write file in binary format

查看:228
本文介绍了以二进制格式写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write the file in binary format. I have the following code with me, but it save the file in text format.

#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();
}

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

In the code I am writing some data and then reading the data again. There is no problem in reading and writing,but I need the file in binary format.

推荐答案

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

Use ofstream::write to write binary data and ifstream::read to read them. Note, that you should save the length of strings because you should know how many bytes to read further.

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();

这篇关于以二进制格式写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆