C++ 标准::向量<;无符号字符>;使用std::ifstream读取二进制文件后保持为空
这是我关于StackOverflow的第一个问题,所以如果我的问题中有什么遗漏或者我没有遵守的规则,我会提前道歉。请编辑我的问题或在评论中告诉我如何改进我的问题,谢谢 <>我尝试用C++读取二进制文件到<>代码STD::vector :使用代码> STD::IFSturi。问题在于,文件似乎已成功读取,但向量仍然为空 下面是我用来读取文件的函数:C++ 标准::向量<;无符号字符>;使用std::ifstream读取二进制文件后保持为空,c++,binaryfiles,stdvector,ifstream,C++,Binaryfiles,Stdvector,Ifstream,这是我关于StackOverflow的第一个问题,所以如果我的问题中有什么遗漏或者我没有遵守的规则,我会提前道歉。请编辑我的问题或在评论中告诉我如何改进我的问题,谢谢 我尝试用C++读取二进制文件到代码STD::vector :使用代码> STD::IFSturi。问题在于,文件似乎已成功读取,但向量仍然为空 下面是我用来读取文件的函数: void readFile(const std::string &fileName, std::vector<unsigned char>
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();
}
当我运行代码时,我得到以下输出:
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;
for(常数自动&i:buf)
{
std::coutreserve()
分配内存,但它不会将分配的区域注册为有效元素
// 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());
您应该使用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());
//备用容量
in.seekg(0,std::ios::end);
//fileContent.reserve(in.tellg());
fileContent.resize(in.tellg());
in.clear();
in.seekg(0,std::ios::beg);
//读入向量
//in.read(reinterpret_cast(fileContent.data()),fileContent.capacity());
in.read(reinterpret_cast(fileContent.data()),fileContent.size());