读取文件中所有可能的十六进制 16 字节序列并打印每个序列

Read all possible HEX 16 bytes sequences in a file and print each one of them

本文关键字:打印 字节 文件 有可能 十六进制 读取      更新时间:2023-10-16

我正在尝试读取文件的所有十六进制二进制字节(您可以在十六进制查看器中看到打开任何十六进制值(文件的任何大小,然后生成并打印所有这些十六进制二进制字节以及新文件以及其中包含所有可能的 16 字节序列。 可能使用 c++,下面是我想要完成的示例:

从这样的文件

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
10 11 12 13

新文件将是这个

00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10
02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11
03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12
04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13

编辑:我正在考虑文件的十六进制值(您可以使用任何类型的十六进制查看器看到的值(

任务不是很复杂。

首先,我们打开输入文件和输出文件。对于两者,我们检查是否可以打开它们。为此,我们使用std::fstream构造函数。看这里。并且,我们将if语句与初始值设定项一起使用。请看这里。

因此,现在两个文件都已打开。在它们离开其作用域后(在if语句结束之后,结束}(,这些文件将由 std::fstream 的析构函数自动关闭。

好,明白了。接下来,我们要从输入文本文件中读取数据。如上所示,文本文件由 2 个字节大小的子字符串组成,对应于文本格式的十六进制值。子字符串由空格分隔。

要阅读它,我们可以使用格式化的输入函数,例如

inputFileStream >> substring0 >> substring1 >> substring2 >> substring3 . . . .

但是由于我们不知道,会有多少字节,我们可以使用std::istream_iterator.使用该迭代器,我们可以迭代源文件中的所有元素。并且,元素将是一个子字符串,如上所述。

您可以想象,>>运算符将被反复调用。

接下来我们要存储所有这些子字符串。为此,我们使用std::vector.这可以动态增长大小。我们将使用所谓的std::vector范围构造函数。请参阅此处,构造函数编号 5。这需要某个源范围的开始和结束迭代器,然后将数据从那里复制到std::vector

开始迭代器是std::istream_iterator,如上所示。结束迭代器将是其默认构造的吊坠:{}。请看这里,构造函数编号 1。

请注意,我们不需要定义std::vector的类型。它将使用 CTAD 自动推断。请看这里。

然后,我们要输出存储在std::vector中的 16 字节数据块。为此,我们使用一个循环,在每次循环运行中增加索引i

此外,我们使用C++算法库中的std::copy_n。请看这里。

我们总是将 16 个子字符串(或更少,如果没有足够的可用(复制到输出文件流中。为此,我们使用std::ostream_iterator,其工作方式类似于输入迭代器。请看这里。

基本上就是这样。

请参阅下面的许多可能的解决方案之一。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
std::string inputFileName{ "input.txt" };
std::string outputFileName{ "output.txt" };
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputFileStream{ inputFileName }; inputFileStream) {
// Open the output file and check, if it could be opened
if (std::ofstream outputFileStream{ outputFileName }; outputFileStream) {
// Read the complete input file. Use range constructor of vector to read all hex sub-strings
std::vector data(std::istream_iterator<std::string>(inputFileStream), {});
int i{};
// Copy 16 bytes from input data to output file, starting with increasing index
do {
std::copy_n(data.begin() + i, (data.size() < 16)? data.size() : 16, std::ostream_iterator<std::string>(outputFileStream, " "));
outputFileStream << 'n';

} while ( i++ < (static_cast<int>(data.size()) - 16));
}
else {
std::cerr << "n*** Error: Could not open output file '" << outputFileName << "'n";
}
}
else {
std::cerr << "n*** Error: Could not open input file '" << inputFileName << "'n";
}
return 0;
}