c++ - 从文件逐行读入 vector<T> 对于二进制数据 C++ 不正确

标签 c++ templates binary stdvector

有模板可以填写vector <T>来自文件:

template<typename T, typename A>
void fill_vector_from_file(const std::string  &filePath, std::vector<T, A> & target)
{
    std::ifstream is(filePath, std::ifstream::in);

    is.seekg(0, std::ifstream::end);
    std::size_t size = is.tellg();
    is.seekg(0, std::ifstream::beg);
    target.reserve(size);

std::string line;
while (std::getline(is, line))
{
    std::istringstream line_in(line);
    while (line_in)
    {
        T val = 0;
        if (line_in >> val)
        {
            target.push_back(val);
        }
    }
}
is.close();

文件中的数据可以是整数或二进制,每行存储一个数字,例如:
对于int:

2 
-3
4

对于二进制:

010
111
001

当我用 std::vector<int> v1 检查模板时对于整数 和 std::vector<unsigned char> v2 , v2[0] 的结果是0而不是 010 .
(我想,我应该使用 unsigned char 来存储二进制文件)

问题:有什么方法可以修改模板,所以v2[0]的结果将如预期 ( 010 )。

最佳答案

第二个文件似乎包含二进制格式的字符串。假设它们总是 3 位长,在这种情况下,如果您使用 std::bitset<3>您将完整阅读每个数字。如果你使用 unsigned char那么你一次只能读一个数字。这是您的功能,通过读取不同文件的示例稍作修改(我想您事先知道的格式)。作为奖励,还有如何转换 std::bitset 的示例 vector 进入unsigned char如果你需要它。

#include <vector>
#include <iostream>
#include <string>
#include <fstream>
#include <bitset>
#include <algorithm> // std::transform

template<typename T, typename A>
void fill_vector_from_file(std::string const &filePath, std::vector<T, A> &vec)
{
    std::ifstream ifs(filePath);
    T val;

    while (ifs >> val)
        vec.push_back(val);
}

int main()
{
    // make sample files
    std::ofstream ofs("myfile.txt");
    ofs << "2\n" << "-3\n" << "4\n";
    ofs.close();
    ofs.open("myfile2.txt");
    ofs << "010\n" << "111\n" << "001\n";
    ofs.close();


    // fill <int> vector
    std::vector<int> vi;
    fill_vector_from_file("myfile.txt", vi);
    // print int vector
    for (auto n : vi)
        std::cout << n << std::endl;


    // fill <bitset> vector 
    std::vector<std::bitset<3>> vbs;
    fill_vector_from_file("myfile2.txt", vbs);
    // print bitset vector
    for (auto n : vbs)
        std::cout << n << std::endl;


    // [OPTIONAL] convert to vector <unsigned char>
    std::vector<unsigned char> vuc(vbs.size());
    std::transform(vbs.begin(), vbs.end(), vuc.begin(),
        [](std::bitset<3> const &bs) -> unsigned char { return static_cast<unsigned char>(bs.to_ulong()); });
    // print vector <unsigned char>
    for (auto n : vuc)
        std::cout << int(n) << std::endl;


    return 0;
}

工作演示:http://coliru.stacked-crooked.com/view?id=42aa04e34e4194c1

2
-3
4
010
111
001
2
7
1

关于c++ - 从文件逐行读入 vector<T> 对于二进制数据 C++ 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49036826/

相关文章:

C++ - 为什么编译器不能推断出包含构造函数参数的函数模板的类型?

c++ - 在 C++ 中的函数参数中使用构造函数是安全的吗?

javascript - 处理 WooCommerce 选定的变体自定义字段条件显示

python - 如何从内存中解码jpg图像?

c# - 如何P/Invoke "__arglist"函数?

c++ - 对象传递给 std::move 但未从中移出?

c++ - 显式特化函数模板的正确方法

c++ - 有人可以向我解释模板解析顺序规则吗?

c - 在 C : ftell returns results that sometimes are off by one 中读取二进制文件

c - 理解定点位模型