我有一個任務,希望從檔案中讀取純文本資料,然后輸出到單獨的二進制檔案。話雖如此,我希望看到二進制檔案的內容不能被人類閱讀理解。但是,當我打開二進制檔案時,內容仍然顯示為純文本。我正在設定這樣的模式_file.open(OUTFILE, std::ios::binary)。我似乎無法弄清楚我錯過了什么。我遵循了其他具有不同實作方法的示例,但顯然我遺漏了一些東西。
出于發布的目的,我創建了一個精簡的測驗用例來演示我正在嘗試的內容。
提前致謝,非常感謝您的幫助!
輸入檔案:test.txt
Hello World
主程式
#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();
}
}
}
uj5u.com熱心網友回復:
如前所述這里,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;
}
然后寫入您的檔案。
uj5u.com熱心網友回復:
簡單來說,標志的std::ios::binary意思是:
不要對我的輸出進行任何調整以幫助提高可讀性或符合作業系統標準。準確地寫下我發送的內容。
在您的情況下,您正在撰寫可讀文本,并且該檔案包含您發送的內容。
您還可以撰寫以文本形式查看時無法理解的位元組。在這種情況下,您的檔案在以文本形式查看時將無法理解。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364604.html
下一篇:|=在C 中有什么作用?[復制]
