(C++)将文件加载到矢量中
(C++) Loading a file into a vector
可能的重复项:
将文件读取到 std::vector中的有效方法?
这可能是一个简单的问题,但是我是C++新手,我无法弄清楚这一点。我正在尝试加载一个二进制文件并将每个字节加载到一个向量。这适用于小文件,但是当我尝试读取大于 410 字节时,程序崩溃并说:
此应用程序已请求运行时在 不寻常的方式。请联系应用程序的支持团队了解更多信息 信息。
我正在窗口上使用代码::块。
这是代码:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
std::vector<char> vec;
std::ifstream file;
file.exceptions(
std::ifstream::badbit
| std::ifstream::failbit
| std::ifstream::eofbit);
file.open("file.bin");
file.seekg(0, std::ios::end);
std::streampos length(file.tellg());
if (length) {
file.seekg(0, std::ios::beg);
vec.resize(static_cast<std::size_t>(length));
file.read(&vec.front(), static_cast<std::size_t>(length));
}
int firstChar = static_cast<unsigned char>(vec[0]);
cout << firstChar <<endl;
return 0;
}
我不确定你的代码有什么问题,但我刚刚用这段代码回答了一个类似的问题。
读取字节unsigned char
:
ifstream infile;
infile.open("filename", ios::binary);
if (infile.fail())
{
//error
}
vector<unsigned char> bytes;
while (!infile.eof())
{
unsigned char byte;
infile >> byte;
if (infile.fail())
{
//error
break;
}
bytes.push_back(byte);
}
infile.close();
相关文章:
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 树莓上的 Libtorch 无法加载 pt 文件,但在 ubuntu 上工作
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- SDL_LoadWAV未加载文件
- 如果流无法加载文件,并且无法打开
- 无法使用 fopen() 加载文件
- 如何在mac上为c++加载文件
- 如何以编程方式知道Adobe Reader完成了加载文件
- 使用loadFromFile()函数加载文件
- 使用微小的xml保存和加载文件
- C++加载文件
- C++从SQL数据库加载文件
- 从"Resource Files"文件夹加载文件C++ Windows 应用程序 (win32)
- 构建时如何在Visual Studio c++中加载文件
- 用dlsym加载文件,无法加载库
- 当在c#中加载c++ dll时,CLR是否会自动加载c++文件的依赖项?
- OpenCV视频捕获不加载文件
- 用char指针加载文件
- TinyXml解析器拒绝正确加载文件
- CMake 错误在 CMakeLists.txt:56 (include): 包含找不到加载文件: gmxVersion