有没有一种优雅的方法来读取二进制文件并将其内容复制到向量<int>
Is there an elegant way to read a binary file and copy its content to a vector<int>
我尝试了此方法:
void read(vector<int> &vec, string filename)
{
std::ifstream file(filename, std::ios::binary | std::fstream::binary);
if (!file.is_open()) throw runtime_error("could not open file");
//std::istreambuf_iterator<char> start(file), end;
std::istream_iterator<int> start(file), end;
//std::istreambuf_iterator<char> start(file), end;
vec = vector<int>(start, end);
file.close();
}
void write(vector<int> &vec, string filename) {
std::ofstream file(filename, std::ios::binary | std::fstream::binary);
if (!file.is_open()) throw runtime_error("could not open file");
copy(
vec.begin(),
vec.end(),
//std::ostreambuf_iterator<char>(file)
std::ostream_iterator<int>(file)
);
file.close();
}
int main(){
vector<int> vec =
{124,5,543,6,756,6,3,234,5,5,765}, vec2;
write(vec, "thing.bin");
read(vec2, "thing.bin");
for (auto&a : vec2) cout << a << endl;
system("PAUSE");
}
评论的代码是我尝试的替代迭代器。
问题是std::ostreambuf_iterator<int>(file)
是文件的无效迭代器。我需要做reinterpret_cast
吗?我是否有义务使用fstream .write()
和read()
?
void read(vector<int> &vec, string filename)
{
std::ifstream file(filename, std::ios::binary | std::fstream::binary);
if (!file.is_open()) throw runtime_error("could not open file");
file.seekg(0, ios_base::end);
int size = file.tellg() / sizeof(int);
vec = vector<int>(size);
file.seekg(0, file.beg);
file.read(reinterpret_cast<char*>(vec.data()), size*sizeof(int));
file.close();
}
void write(vector<int> &vec, string filename) {
std::ofstream file(filename, std::ios::binary | std::fstream::binary);
if (!file.is_open()) throw runtime_error("could not open file");
file.write(reinterpret_cast<const char*>(vec.data()), vec.size() * sizeof(int));
file.close();
}
int main(){
vector<int> vec =
{0,1,2,3,-1,127,128,1023,1024}, vec2;
write(vec, "thing.bin");
read(vec2, "thing.bin");
for (auto&a : vec2) cout << a << endl;
return 0;
}
相关文章:
- 将指向给定子类的指针从一个向量复制到另一个向量
- 为共享 ptr 向量实现复制 c'tor?
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 具有 STL 向量类型成员的类的复制内存
- 将字符向量复制到另一个向量
- 如何从字符串向量构造对象并避免复制?
- 在 Cython 中将C++向量转换为 numpy 数组,而无需复制
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 将shared_ptr的向量复制到抽象基的派生类
- 如何避免将向量的完整值复制到另一个容器
- C++向量的哪一部分在传递给函数时被复制
- 如何在向量列表初始化时避免对象复制以及如何延长临时的生存期
- 如何将 int4 数组复制到 int8 向量中
- 复制向量本身
- 在 C++11 中高效复制向量
- 复制向量为成员变量的对象的构造函数
- 不复制向量类成员
- 在不使用元素复制赋值运算符的情况下复制向量 - 可移植性
- 在复制构造函数中复制向量的向量
- 从常量变量复制向量