c++ - 将文件存储在 unsigned char 数组中并打印

标签 c++ arrays

我使用下面的代码读取一个二进制文件(在我的例子中是 .docx 文件)并将其存储在无符号字符数组中,而不仅仅是字符(从这里引用 Reading and writing binary file )

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input("C:\\test.docx", std::ios::binary);
    std::vector<unsigned char> buffer((std::istreambuf_iterator<unsigned char>(input)), 
                                      (std::istreambuf_iterator<unsigned char>()));
}

现在我有两个问题。

首先我想知道,这是读取 unsigned char 数组中的 .docx 文件的正确方法吗?或者有更好的选择吗?

其次,我需要打印在 unsigned char 数组中读取的文件内容,只是为了验证它是否已正确读取文件。如何实现?

最佳答案

如果您可以将整个文件保存在内存中,那么这是一种不错的方法。如果你想分部分读取文件,你应该遍历它。它的一个用例是通过网络传输它 - 在那里,您不需要内存中的整个文件。

关于打印文件,可以打印读取的字节,例如,像这样:

#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
#include <iomanip>

int main()
{
    std::ifstream input("C:\\test.docx", std::ios::binary);
    std::vector<unsigned char> buffer((std::istreambuf_iterator<unsigned char>(input)), 
                                      (std::istreambuf_iterator<unsigned char>()));

    std::cout << std::hex;
    for (unsigned char b : buffer)
        std::cout << "0x" << std::setfill('0') << std::setw(2) << (int)b << " "; 
    std::cout << std::dec << std::endl;
}

如果您的意思是打印文件的内容以查看一些熟悉的文本,那将无法直接工作。 docx 文件使用 Open XML File Format ,首先,使它们成为一个 zip 文件。在 zip 文件中,您会发现文档中数据的 XML 表示形式,它们是可读的。

关于c++ - 将文件存储在 unsigned char 数组中并打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942584/

相关文章:

c++ - C 中用 1 替换 0 的宏

python & c-c++扩展模块案例段错误

c++ - Arduino 十六进制转十进制

python - 设置两个数组相等

在 C 中将长整数转换为 int 数组

c - 为什么 getchar() 没有收到任何输入?

arrays - Tensorflow 中张量和多维矩阵有什么区别?

c++ - 为什么当通过 Objective-c 类调用时,C++ 实例会自动调用构造函数和析构函数?

c++ - std::map 的部分反序列化

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP