使用std::ifstream读取二进制文件后std::vector<unsignedchar>保持为空
这是我在 StackOverflow 上的第一个问题,所以如果我的问题中遗漏了任何内容或我没有遵循的某些规则,我会提前道歉。请编辑我的问题或在评论中告诉我我应该如何改进我的问题,谢谢。
我正在尝试std::vector<unsigned char>使用std::ifstream. 问题是文件似乎已成功读取,但向量仍为空。
这是我用于读取文件的函数:
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():
std::vector<unsigned char> buf;
readFile("file.dat", buf);
std::cout << "buf size: " << buf.size() << std::endl;
当我运行代码时,我得到以下输出:
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;
我得到空输出。
我检查过的东西
file.dat与程序在同一目录中file.dat不为空
那么,我做错了什么吗?为什么读取后向量为空?
回答
reserve() 分配内存,但它不会将分配的区域注册为有效元素。
您应该使用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());
THE END
二维码