如何在 C++ 中将 vector<uint_8> 写入文件?

How to write vector<uint_8> to a file in c++?

我填充了 vector 数据,想使用 C++ 将此数据写入文件?尝试过但没有找到任何参考。

const std::vector<uint8_t>  buffer; // let's assume that i'ts filled with values
std::ofstream out("file.txt", std::ios::out | std::ios::binary);
out.write(&buffer, buffer.size());

但没有成功。以二进制模式打开文件是否正确?

您可以按照其他人的建议转换数据指针:

#include <vector>
#include <fstream>

int main()
{
    std::vector<uint8_t> temp;
    temp.push_back(97);
    temp.push_back(98);
    temp.push_back(99);

    const std::vector<uint8_t>  buffer(temp); // let's assume that i'ts filled with values
    std::ofstream out("file.txt", std::ios::out | std::ios::binary);
    out.write(reinterpret_cast<const char*>(buffer.data()), buffer.size());
    out.close();
}

输出:file.txt

abc

如果您通过包含二进制数据 (uint8_t) 的文本文件查看此文件,您将希望在文件中看到以下内容,其中每个 uint8_t 对应一个 ascii 符号:

https://www.asciitable.com/

如果您打算将整数值而不是原始二进制数据写入文件,那么您可以这样做:

#include <vector>
#include <fstream>
#include <string>

int main()
{
    std::vector<uint8_t> temp;
    temp.push_back(97);
    temp.push_back(98);
    temp.push_back(99);

    const std::vector<uint8_t>  buffer(temp); // let's assume that i'ts filled with values
    std::ofstream out("file.txt", std::ios::out | std::ios::binary);

    for (auto v : buffer)
    {
        std::string str = std::to_string(v);
        out.write(str.c_str(), str.length());
    }
    out.close();
}

输出:file.txt

979899