不能写入的1和0字符串二进制文件,C ++ [英] Can't write string of 1 and 0 to binary file, C++

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

问题描述

我有一个接收指向一个字符串文件的名称即可打开并以code。与1和0的功能;
codedLine 包含类似的 010100110101110101010011
写二进制文件后,我有完全一样的... ...吗,你会推荐?谢谢你。

 无效codeFILE(字符* S)
{
    字符* BUF =新的char [maxStringLength]
    性病:: ifstream的fileTo code(S);
    的std :: ofstream的codedFile(codedFile.txt的std :: IOS ::二进制);
    如果(!fileTo code.is_open())
        返回;
    而(fileTo code.getline(BUF,maxStringLength))
    {
        标准::字符串codedLine = $ C $克莱恩(BUF);
        codedFile.write(codedLine.c_str(),codedLine.size());
    }
    codedFile.close();
    fileTo code.close();
}


解决方案

  

写二进制文件后,我有完全一样的...


我想你想的的std ::字符串输入转换为等值的二进制。

您可以使用 和std :: bitset&LT ;> 类字符串转换为二进制值,反之亦然。直接写入字符串中的字符值的二进制重新presentations文件结果0 1

这是例子,如何使用它:

 的std ::字符串zeroes_and_ones =1011100001111010010;
//定义,可容纳的sizeof(无符号长)位一个bitset
和std :: bitset<的sizeof(无符号长)* 8'比特(zeroes_and_ones);无符号长binary_value = bits.to_ulong();//写的二进制值到文件
codedFile.write((为const char *)及binary_value,sizeof的(无符号长));

注意结果
上述样品可以与 C ++ 11 标准。对于早期版本的和std :: bitset 不能直接从字符串初始化。 >但是,它可以使用运营商的GT填补。()的std :: istringstream 例如

I have the function that receives a pointer to a string with a name of file to open and to code with 1 and 0; codedLine contains something like 010100110101110101010011 After writing to binary file I have exactly the same...Would would you recommend? Thank you.

    void codeFile(char *s)
{
    char *buf = new char[maxStringLength];
    std::ifstream fileToCode(s);
    std::ofstream codedFile("codedFile.txt", std::ios::binary);
    if (!fileToCode.is_open())
        return;
    while (fileToCode.getline(buf, maxStringLength))
    {
        std::string codedLine = codeLine(buf);
        codedFile.write(codedLine.c_str(), codedLine.size());
    }
    codedFile.close();
    fileToCode.close();
}

解决方案

After writing to binary file I have exactly the same...

I suppose you want to convert the std::string input to its binary equivalent.

You can use the std::bitset<> class to convert strings to binary values and vice versa. Writing the string directly to the file results in binary representations of the character values '0' and '1'.

An example how to use it:

std::string zeroes_and_ones = "1011100001111010010";
// Define a bitset that can hold sizeof(unsigned long) bits
std::bitset<sizeof(unsigned long) * 8> bits(zeroes_and_ones);

unsigned long binary_value = bits.to_ulong();

// write the binary value to file
codedFile.write((const char*)&binary_value, sizeof(unsigned long));

NOTE
The above sample works with standards. For earlier version the std::bitset can't be initialized directly from the string. But it can be filled using the operator>>() and std::istringstream for example.

这篇关于不能写入的1和0字符串二进制文件,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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