29

Thanks to Mats Petersson for the explanation on how to to copy vector to array, it's seems work. Here is the code snipet:

#include <iostream>
#include <string.h>
#include <vector>
#include <fstream>

using namespace std;

class Student
  {
    private:
    char m_name[30];
    int m_score;

    public:
    Student()
      {

      }
    Student(const Student& copy)
      {
           m_score = copy.m_score;   //wonder why i can use this statment as
           strncpy(m_name, copy.m_name, 30); //declare it private
      }
      Student(const char name[], const int &score)
      :m_score(score)
      {
           strncpy(m_name, name, 30);
      }
      void print() const
      {
           cout.setf(ios::left);
           cout.width(20);
           cout << m_name << " " << m_score << endl;
      }
      };


      int main()
      {
        vector<Student> student;
        student.push_back(Student("Alex",19));
        student.push_back(Student("Maria",20));
        student.push_back(Student("muhamed",20));
        student.push_back(Student("Jeniffer",20));
        student.push_back(Student("Alex",20));
        student.push_back(Student("Maria",21));
      {
      Student temp[student.size()];
      unsigned int counter;
      for(counter = 0; counter < student.size(); ++counter)
      {
        temp[counter] = student[counter];
      }

      ofstream fout("data.dat", ios::out | ios::binary);
      fout.write((char*) &temp, sizeof(temp));
      fout.close();
      }

      vector<Student> student2;
      ifstream fin("data.dat", ios::in | ios::binary);

      {
        fin.seekg(0, ifstream::end);
        int size = fin.tellg() / sizeof (Student);
        Student temp2[size];
        fin.seekg(0, ifstream::beg);
        fin.read((char*)&temp2, sizeof(temp2));
        int counter;
        for(counter = 0; counter <6; ++counter)
        {
        student2.push_back(temp2[counter]);
        }
        fin.close();
      }
      vector<Student>::iterator itr = student2.begin();
      while(itr != student2.end())
      {
        itr->print();
        ++itr;
      }
      return 0;
      }

But I guest this method will waste huge memory and be cumbersome. Maybe I will consider writing it Mr. with ocelot and other suggestions. Thanks everyone for the answer.

4

4 回答 4

25

要将一个PODvector<T> 存储在文件中,您必须写入向量的内容,而不是向量本身。您可以使用第一个元素的地址访问原始数据&vector[0](假设它包含至少一个元素)。要获得原始数据长度,请将向量中的元素数乘以一个元素的大小:

strm.write(reinterpret_cast<const char*>(&vec[0]), vec.size()*sizeof(T));

从文件中读取向量时也是如此;元素计数是文件总大小除以一个元素的大小(假设您只在文件中存储一种类型的 POD):

const size_t count = filesize / sizeof(T);
std::vector<T> vec(count);
strm.read(reinterpret_cast<char*>(&vec[0]), count*sizeof(T));

这仅适用于您可以根据文件大小计算元素数量(如果您只存储一种类型的 POD 或所有向量包含相同数量的元素)。如果您有具有不同 POD 且长度不同的向量,则必须在写入原始数据之前将向量中的元素数写入文件。

此外,当您在不同系统之间以二进制形式传输数字类型时,请注意字节顺序

于 2012-12-30T09:30:43.717 回答
24

您正在写入文件矢量结构,而不是其数据缓冲区。尝试将写入程序更改为:

 ofstream fout("data.dat", ios::out | ios::binary);
 fout.write((char*)&student[0], student.size() * sizeof(Student));
 fout.close();

而不是从文件大小计算向量的大小,最好先写向量大小(对象数)。在这种情况下,您可以将其他数据写入同一文件。

 size_t size = student.size();
 fout.write((char*)&size, sizeof(size));
于 2012-12-30T09:27:39.900 回答
4

您可能无法以二进制(您正在做的方式)写入任何std::vector内容,因为该模板包含内部指针,并且写入和重新读取它们是没有意义的。

一些一般性建议:

  • 不要以二进制形式编写任何 STL 模板容器(如std::vectoror std::map),它们肯定包含您真的不想按原样编写的内部指针。如果您真的需要编写它们,请实现您自己的写入和读取例程(例如,使用 STL 迭代器)。

  • 避免随意使用strcpy。如果名称超过 30 个字符,您的代码将崩溃。至少,使用strncpy(m_name, name, sizeof(m_name));(但即使这样对于 30 个字符的名称也不好用)。其实m_name应该是一个std::string

  • 显式序列化您的容器类(通过处理每个有意义的成员数据)。您可以考虑使用JSON表示法(或者可能是YAML,或者甚至是 XML - 我觉得太复杂所以不推荐)来序列化。它为您提供了一种文本转储格式,您可以使用标准编辑器(例如emacsgedit)轻松地对其进行检查。你会发现很多序列化的免费库,例如jsoncpp和许多其他库。

  • 学习编译g++ -Wall -g和使用gdb调试器和valgrind内存泄漏检测器;也学会使用make和写你的Makefile-s。

  • 利用 Linux 是免费软件的优势,因此您可以查看它的源代码(即使 STL 标头很复杂,您也可能想研究 stdc++ 实现)。

于 2012-12-30T08:17:26.010 回答
3

对于函数 read() 和 write(),您需要所谓的“普通旧数据”或“POD”。这基本上意味着类或结构内部必须没有指针,也没有虚函数。vector 的实现当然有指针——我不确定虚函数。

您将不得不编写一个函数来一次存储一个学生(或者将一群学生转换为字节数组 [不是向量] 或类似的 - 但这更复杂)。

您不能将非 POD 数据(尤其是指针)写入二进制文件的原因是,当您再次读回数据时,您几乎可以肯定地打赌,内存布局已经与您写入时发生了变化。这有点像试图在商店的同一个停车位停车 - 当您下次出现时,其他人将停在入口的第三个位置,因此您必须选择另一个位置。将编译器分配的内存视为停车位,将学生信息视为汽车。

[从技术上讲,在这种情况下,情况更糟-您的向量实际上并不包含班级内的学生,这就是您正在写入文件的内容,因此您甚至没有保存有关学生的信息,而只是保存了信息关于他们所在的位置(停车位的数量)]

于 2012-12-30T08:20:53.013 回答