繁体   English   中英

标准::向量<unsigned char>使用 std::ifstream 读取二进制文件后仍然为空</unsigned>

[英]std::vector<unsigned char> remains empty after reading binary file using std::ifstream

这是我在 StackOverflow 上的第一个问题,所以如果我的问题中缺少任何内容或我未遵循的某些规则,我提前道歉。 请编辑我的问题或在评论中告诉我应该如何改进我的问题,谢谢。

我正在尝试使用std::ifstream将二进制文件读入 C++ 中的std::vector<unsigned char> 问题是文件似乎已成功读取,但向量仍然为空。

这是我用于读取文件的 function:

void readFile(const std::string &fileName, std::vector<unsigned char> &fileContent)
{
    std::ifstream in(fileName, std::ifstream::binary);

    // reserve capacity
    in.seekg(0, std::ios::end);
    fileContent.reserve(in.tellg());
    in.clear();
    in.seekg(0, std::ios::beg);

    // read into vector
    in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.capacity());

    if(in)
        std::cout << "all content read successfully: " << in.gcount() << std::endl;
    else
        std::cout << "error: only " << in.gcount() << " could be read" << std::endl;

    in.close();
}

这就是我在main()中调用 function 的方式:

std::vector<unsigned char> buf;
readFile("file.dat", buf);
std::cout << "buf size: " << buf.size() << std::endl;

当我运行代码时,我得到以下 output:

all content read successfully: 323
buf size: 0

当我尝试像这样打印向量中的项目时:

for(const auto &i : buf)
{
    std::cout << std::hex << (int)i;
}
std::cout << std::dec << std::endl;

我得到空的 output。

我检查过的东西

  • file.dat与程序在同一目录中
  • file.dat不为空

那么,是不是我做错了什么? 为什么读取后向量为空?

reserve()分配 memory,但它没有将分配的区域注册为有效元素。

您应该使用resize()添加元素并使用size()来计算元素。

    // reserve capacity
    in.seekg(0, std::ios::end);
    //fileContent.reserve(in.tellg());
    fileContent.resize(in.tellg());
    in.clear();
    in.seekg(0, std::ios::beg);

    // read into vector
    //in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.capacity());
    in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.size());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM