首页 > 解决方案 > 将真正的二进制文件写入文件

问题描述

我目前正在从事一个项目,以从文件中读取二进制数据并对其进行处理并再次将其写回。到目前为止,读取效果很好,但是当我尝试将存储在字符串中的二进制数据写入文件时,它会将二进制文件作为文本写入。我认为这与开放模式有关。这是我的代码:

void WriteBinary(const string& path, const string& binary)
{
    ofstream file;
    file.open(path);
    std::string copy = binary;
    while (copy.size() >= 8)
    {
        //Write byte to file
        file.write(binary.substr(0, 8).c_str(), 8);
        copy.replace(0, 8, "");
    }
    file.close();
}

在上面的函数中,binary参数如下所示:0100100001100101011011000110110001101111

标签: c++filebinarybinaryfiles

解决方案


在“aschelper”的帮助下,我能够为这个问题创建一个解决方案。在将二进制字符串写入文件之前,我将其转换为通常的表示形式。我的代码如下:

// binary is a string of 0s and 1s. it will be converted to a usual string before writing it into the file.
void WriteBinary(const string& path, const string& binary)
{
    ofstream file;
    file.open(path);
    string copy = binary;

    while (copy.size() >= 8)
    {
        char realChar = ByteToChar(copy.substr(0, 8).c_str());
        file.write(&realChar, 1);
        copy.replace(0, 8, "");
    }
    file.close();
}


// Convert a binary string to a usual string
string BinaryToString(const string& binary)
{
    stringstream sstream(binary);
    string output;
    while (sstream.good())
    {   
        bitset<8> bits;
        sstream  >> bits;
        char c = char(bits.to_ulong());
        output += c;
    }
    return output;
}

// convert a byte to a character
char ByteToChar(const char* str) {
    char parsed = 0;
    for (int i = 0; i < 8; i++) {
        if (str[i] == '1') {
            parsed |= 1 << (7 - i);
        }
    }
    return parsed;
}

推荐阅读