c++使用包含vector的类随机访问文件
c++ use random access file with class that include a vector
我想从一个包含vector<int>
的类中创建一些对象,并且我想将该对象保存在一个文件中,以便下次从该文件中读取,但是程序不能在该类的新对象中正确读取类数据。
例如,它可以读取我的向量的大小(即500),但它不能读取向量单元格的值!有时,当我的文件包含两个或多个对象时,程序将终止并不打印任何内容。
class my_class {
int counter;
vector<int> v;
public:
my_class():counter(0),v(500,0){}
void fill_vec(int x) {
v.at(counter++)=x;
}
const vector<int> & get_vec () const {
return v;
}
const my_class & operator=(const my_class &inp){
v=inp.v;
counter=inp.counter;
return *this;
}
};
void write_to_file(my_class x) {
fstream opf("/home/rzz/file/my_file.dat", ios::in |ios::out|ios::binary); // my file has been created before - no problem to creat file here
opf.seekp(0,ios::end);
opf.write(reinterpret_cast < char *> (&x),sizeof(my_class));
}
my_class read_from_file(int record_number){
my_class temp;
fstream opf("/home/rzz/file/my_file.dat", ios::in |ios::out|ios::binary);
opf.seekg(record_number*sizeof(my_class), ios::beg);
opf.read(reinterpret_cast< char *> (&temp),sizeof(my_class));
return temp;
}
int main() {
my_class zi;
zi.fill_vec(15);
write_to_file(zi);
my_class zi2=read_from_file(0);
vector<int> vec;
vec=(zi2.get_vec());
cout<<zi2.get_vec().size();// right answer , print 500 correctly
cout<<"first element of vector ( should be 15 ) : "<<vec.at(0);//print 0 here , that is wrong
return 0;
}
有人能帮我吗?
写出某个东西的位图像通常不会给你你可以重读的数据;事实是你需要这样做的reinterpret_cast
会警告您已打开非常薄的冰。您需要定义文件的格式或者使用现有的格式(XDR或Google的)协议缓冲区,如果您想要二进制,XDR要简单得多实现,至少如果您将可移植性限制为具有32位2's补位整型和IEEE浮点数);然后格式化你的数据到它,在一个char
缓冲区,然后写
既然我被要求举个例子:
为了简单起见,我将格式化为一个缓冲区;通常,我会写一个oxdrstream类,并直接格式化为输出流;但这涉及到更复杂的错误处理。我还将假设一个32位的2的补整类型。这是而不是保证,有些系统不是这样的,但是它们相当罕见。(这里,我使用uint32_t
和int32_t
确保代码不会在不能编译的系统上编译支持它。)
void
insertUInt( std::vector<char>& dest, uint32_t value )
{
dest.push_back( (value >> 24) & 0xFF );
dest.push_back( (value >> 16) & 0xFF );
dest.push_back( (value >> 8) & 0xFF );
dest.push_back( (value ) & 0xFF );
}
void
insertInt( std::vector<char>& dest, int32_t value )
{
return InsertUInt( dest, static_cast<uint32_t>(value) );
}
void
insertIntArray( std::vector<char>& dest, std::vector<int> const& value )
{
assert( value.size() <= std::numeric_limits<uint32_t>::max() );
insertUInt( value.size() );
for ( int i: value ) {
insertInt( dest, i );
}
}
(这段代码或多或少假设int32_t
与int
。否则,您需要进行一些额外的边界检查
相关文章:
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 如何为我的容器实现随机访问迭代器?
- 对于C++随机访问迭代器(矢量迭代器),迭代器之间的差异是如何计算的?
- 对于随机访问迭代器(矢量迭代器),迭代器C++样式指针吗?
- Deque 中元素的随机访问如何提供恒定的时间复杂度?
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- 随机访问迭代器:我错过了什么?
- 随机访问元组向量中的元组值
- 有没有办法在C++中制作无锁"counter"随机访问迭代器?
- 当 95% 情况下的值为 0 或 1 时,对非常大的数组进行随机访问的任何优化
- 如何确保函数模板的参数是随机访问迭代器
- C++基于现有随机访问迭代器的反向迭代器
- C++ 写入随机访问文件
- 如何实现随机访问迭代器的"less than operator"?
- 随机访问迭代器和Deque
- 如何创建一个随机访问式的Rreference以访问.RC文件中定义的资源
- 在链表上实现随机访问迭代器
- 随机访问文件格式,用于分层组织的二进制文件和文本文件