用输出流创建的二进制输出文件的内容 [英] Content of Binary Output File Created With Output Stream

查看:220
本文介绍了用输出流创建的二进制输出文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码编译并执行。它只是将内容
打印成二进制格式。但是输出不同于我的预期,即:

This code compiles and does execute. It simply print the content into a binary format. However the output differs from what I expected, namely:


  1. 输出文件的大小应该比使用std :: cout创建的小。 / li>
  2. 输出文件的内容应该压缩,因此当我们在编辑器中打开它时,
    我们不能看到内容。

但是为什么下面的代码不能像我希望的那样做呢?如何修改它?

But why the code below doesn't do as I hope it does? How can I modify it accordingly?

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

void WriteStr2BinFh(const string& St, ostream &fn)
{
   fn.write(St.c_str(), St.length());
}



int main  ( int arg_count, char *arg_vec[] ) {

    vector <string> Tags;
   // In principle we have millions of such tags
   // Hence we need to compress it into binary output.
    Tags.push_back("0000000000");
    Tags.push_back("0000101110");
    Tags.push_back("0133030122");
    Tags.push_back("0133132033");
    Tags.push_back("1002013320");
    Tags.push_back("1111111111");
    Tags.push_back("1301013133");
    Tags.push_back("3010112111");
    Tags.push_back("3203012113");
    Tags.push_back("3203012212");

    //prn_vec<string>(Tags, "\t");
    //cout << endl;

    ofstream outfile;
    outfile.open("MyOut.bin", ios::binary|ios::out);

    for (unsigned i=0; i <Tags.size(); i++) {
         WriteStr2BinFh(Tags[i]+"\t",outfile);
    }

    outfile.close();

    return 0;
}


推荐答案

格式(不是文本):

void WriteStr2BinFh(const string& St, ostream &fn)
{
char *p = 0;
long l = strtol(St.c_str(), &p);
fn << l;
}

你必须知道类型long类型有一些最大值,可能必须将你的字符串分割成n个片段并保存为n个长整型。

You must be aware that types like long have some maximum values, so you will probably have to split your string into n pieces and save as n longs.

这篇关于用输出流创建的二进制输出文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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