【发布时间】:2012-10-19 22:02:57
【问题描述】:
我有一个结构
typedef struct student
{
char name[10];
int age;
vector<int> grades;
} student_t;
我正在将其内容写入二进制文件。
我在不同的时间写入,文件中有很多数据是从这个结构写入的。
现在,我想将二进制文件中的所有数据读取到结构中。 我不确定如何(动态地)为结构分配内存,以便结构可以容纳结构上的所有数据。
你能帮我解决这个问题吗?
代码:
#include <fstream>
#include <iostream>
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <iterator>
using namespace std;
typedef struct student
{
char name[10];
int age;
vector<int> grades;
}student_t;
int main()
{
student_t apprentice[3];
strcpy(apprentice[0].name, "john");
apprentice[0].age = 21;
apprentice[0].grades.push_back(1);
apprentice[0].grades.push_back(3);
apprentice[0].grades.push_back(5);
strcpy(apprentice[1].name, "jerry");
apprentice[1].age = 22;
apprentice[1].grades.push_back(2);
apprentice[1].grades.push_back(4);
apprentice[1].grades.push_back(6);
strcpy(apprentice[2].name, "jimmy");
apprentice[2].age = 23;
apprentice[2].grades.push_back(8);
apprentice[2].grades.push_back(9);
apprentice[2].grades.push_back(10);
// Serializing struct to student.data
ofstream output_file("students.data", ios::binary);
output_file.write((char*)&apprentice, sizeof(apprentice));
output_file.close();
// Reading from it
ifstream input_file("students.data", ios::binary);
student_t master;
input_file.seekg (0, ios::end);
cout << input_file.tellg();
std::vector<student_t> s;
// input_file.read((char*)s, sizeof(s)); - dint work
/*input_file >> std::noskipws;
std::copy(istream_iterator(input_file), istream_iterator(), std::back_inserter(s));*/
while(input_file >> master) // throws error
{
s.push_back(master);
}
return 0;
}
【问题讨论】:
-
我不明白你的问题。
vector已经处理动态分配。你的意思是你有一个装满student_t的容器要动态分配? -
说我将一个结构数组说 student_t[5] 写入二进制文件并执行 4 次。我想将二进制文件中的数据提取到结构中。但是我不知道已经编写了多少这样的结构(因为用户可以编写任意数量的这样的结构数组)。我想知道一种将动态数据拉到结构上的方法。
-
你必须记录写了多少个结构体。
-
为什么在一个地方使用vector,但是(1)不使用vector来获取多个学生和(2)使用c风格的字符串而不是
std::string?我的意思是,我为了学习低级的东西而忽略了高级功能,但使用它们的一半似乎很愚蠢。 -
如果您关心的是二进制文件,您可以测试 EOF (=End Of File)。如果是关于代码的 C++ 部分,您应该使用
vector<student_t>。向量已经处理了动态分配,您可以在它们上调用.size()。