c++使用包含vector的类随机访问文件

c++ use random access file with class that include a vector

本文关键字:随机 访问 文件 vector 包含 c++      更新时间:2023-10-16

我想从一个包含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_tint32_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_tint。否则,您需要进行一些额外的边界检查