这是我在StackOverflow上遇到的第一个问题,因此,如果我的问题中遗漏了某些内容或未遵循的某些规则,我向您致歉。请编辑我的问题或在评论中告诉我如何改善我的问题,谢谢。
我正在尝试使用将二进制文件读入std::vector<unsigned char>
C ++中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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句