【发布时间】:2022-01-02 06:16:06
【问题描述】:
我有一个任务,希望从文件中读取纯文本数据,然后输出到单独的二进制文件。话虽如此,我希望看到二进制文件的内容对于人类阅读来说是不可理解的。但是,当我打开二进制文件时,内容仍然显示为纯文本。我正在设置这样的模式_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] = '\0';
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();
}
}
}
【问题讨论】:
-
operator<<()始终呈现文本,无论您是否以二进制模式打开文件。请改用write()。 -
如果您将文本写入作为二进制文件打开的文件,唯一的区别是换行符不会转换为依赖于操作系统的换行符,而是保留在写入参数中操作。
-
以二进制模式打开文件并不意味着文件看起来像垃圾。不管你怎么写,一个“A”看起来仍然像一个“A”。
-
“我希望看到二进制文件的内容不适合人类阅读” 为什么会这样?您正在将可读文本写入文件。 “二进制”并不意味着“难以理解”。
标签: c++ binaryfiles ofstream