C++ ofstream 二进制模式 - 书面文件看起来仍然像纯文本

C++ ofstream Binary Mode - Written file still looks like plain text

我有一个作业需要从文件中读取纯文本数据,然后输出到一个单独的二进制文件。话虽如此,我希望看到二进制文件的内容对人类阅读来说是不可理解的。但是,当我打开二进制文件时,内容仍显示为纯文本。我正在设置这样的模式 _file.open(OUTFILE, std::ios::binary)。我似乎无法弄清楚我错过了什么。我遵循了其他具有不同实现方法的示例,但显然我遗漏了一些东西。

为了发帖,我创建了一个精简的测试用例来演示我正在尝试的内容。

在此先致谢,非常感谢您的帮助!

输入文件:test.txt

Hello World

main.cpp

#include <iostream>
#include <fstream>

using namespace std;

#define INFILE "test.txt"
#define OUTFILE "binary-output.dat"


int main(int argc, char* argv[]) {

    char* text = nullptr;
    int nbytes = 0;
    // open text file
    fstream input(INFILE, std::ios::in);
    if (!input) {
        throw "\n***Failed to open file " + string(INFILE) + " ***\n";
    }

    // copy from file into memory
    input.seekg(0, std::ios::end);
    nbytes = (int)input.tellg() + 1;

    text = new char[nbytes];

    input.seekg(ios::beg);
    int i = 0;
    input >> noskipws;
    while (input.good()) {
        input >> text[i++];
    }
    text[nbytes - 1] = '[=11=]';
    cout << "\n" << nbytes - 1 << " bytes copied from file " << INFILE << " into memory (null byte added)\n";

    if (!text) {
        throw "\n***No data stored***\n";
    } else {
        // open binary file for writing
        ofstream _file;
        _file.open(OUTFILE, std::ios::binary);

        if (!_file.is_open()) {
            throw "\n***Failed to open file***\n";
        } else {
            // write data into the binary file and close the file
            for (size_t i = 0U; i <= strlen(text); ++i) {
                _file << text[i];
            }

            _file.close();
        }
    }
}

here所述,std::ios::binary实际上不会为您编写二进制文件。基本上,它与 std::ios::out 相同,只是 \n 之类的内容不会转换为换行符。

您可以使用 <bitset> 将文本转换为二进制,如下所示:

#include <iostream>
#include <vector>
#include <bitset>

int main() {
    std::string str = "String in plain text";
    std::vector<std::bitset<8>> binary; // A vector of binaries

    for (unsigned long i = 0; i < str.length(); ++i) {
        std::bitset<8> bs4(str[i]);
        binary.push_back(bs4);
    }

    return 0;
}

然后写入你的文件。

用最简单的话来说,标志 std::ios::binary 表示:

Do not make any adjustments to my output to aid in readability or conformance to operating system standards. Write exactly what I send.

在您的情况下,您正在编写可读文本,并且文件包含您发送的内容。

您还可以编写在作为文本查看时难以理解的字节。在这种情况下,您的文件在以文本形式查看时将难以理解。