我创建了一个班级Student
学生班:
class Student
{
friend ostream& operator<<(ostream& os, const Student& s)
{
return os <<
"Roll no.: " << s.roll_no << '\n' <<
"Name: " << s.name << '\n' <<
"Phone no.: " << s.phone_no << '\n' <<
"Address: " << s.address << '\n';
}
public:
Student() = default;
Student(int r, const char* n, int p_no, const char* a):
roll_no(r), phone_no(p_no)
{
strcpy(name, n);
strcpy(address, a);
}
int get_roll() const
{
return roll_no;
}
private:
int roll_no;
char name[40 + 1];
int phone_no;
char address[100 + 1];
};
在StudentList
类中,我将一些Student对象存储在二进制文件中。
class StudentList
{
public:
StudentList(const string& fname):
filename(fname)
{
make_index();
}
Student get_student(int roll)
{
fstream ifs(filename, ios::in | ios::binary);
int pos = index[roll];
ifs.seekg(pos * sizeof(Student));
Student s;
ifs.read(reinterpret_cast<char*>(&s), sizeof(s));
return s;
}
void change_student(Student s)
{
fstream ofs(filename, ios::out | ios::binary);
int pos = index[s.get_roll()];
ofs.seekp(pos * sizeof(s));
ofs.write(reinterpret_cast<const char*>(&s), sizeof(s));
}
void add_student(Student s)
{
fstream ofs(filename, ios::out | ios::binary | ios::app);
ofs.write(reinterpret_cast<const char*>(&s), sizeof(s));
int total_no = index.size() + 1;
index[s.get_roll()] = total_no - 1;
}
private:
string filename;
map<int, int> index;
void make_index()
{
fstream ifs(filename, ios::in | ios::binary);
int pos = 0;
if (ifs.is_open()) {
while (!ifs.eof()) {
Student s;
ifs.read(reinterpret_cast<char*>(&s), sizeof(s));
index[s.get_roll()] = pos;
pos++;
}
}
}
};
但是,此代码输出错误。运行程序时,二进制文件不存在。所以StudentList::make_index
在构造函数中调用它时会创建一个新文件。
int main()
{
StudentList sl("student.dat");
sl.add_student(Student(14, "V", 12, "14/14"));
sl.add_student(Student(1, "A", 12, "13/13 Tollygunge"));
cout << sl.get_student(14) << '\n';
cout << sl.get_student(1) << '\n';
sl.change_student(Student(1, "B", 12, "14/14, Bosepukur Road"));
cout << sl.get_student(14) << '\n';
cout << sl.get_student(1) << '\n';
return 0;
}
输出:
Roll no.: 14
Name: V
Phone no.: 12
Address: 14/14
Roll no.: 1
Name: A
Phone no.: 12
Address: 13/13 Tollygunge
Roll no.: 0
Name:
Phone no.: 0
Address:
Roll no.: 1
Name: B
Phone no.: 12
Address: 14/14, Bosepukur Road
尝试使用gdb进行调试时,我发现函数StudentList::change_student(Student)
无法正常工作。在函数中,尽管使用seekp在文件中的第一个Student
对象之后设置写入位置(作为pos
= 1),但第一个Student
对象也以某种方式被修改。登记/>
修改
我想我发现了错误。在StudentList::change_student(Student s)
中更改此行:
fstream ofs(filename, ios::out | ios::binary);
为:
fstream ofs(filename, ios::out | ios::binary | ios::in);
给出正确的输出 输出:
Roll no.: 14
Name: V
Phone no.: 12
Address: 14/14
Roll no.: 1
Name: A
Phone no.: 12
Address: 13/13 Tollygunge
Roll no.: 14
Name: V
Phone no.: 12
Address: 14/14
Roll no.: 1
Name: B
Phone no.: 12
Address: 14/14, Bosepukur Road
最有可能是Aumnayan建议的,之前的开放模式是在change_student函数中删除文件的内容。
答案 0 :(得分:3)
尝试在change_student方法中添加ios :: app标志。我缝合记住,ios :: out是破坏性的,这将留下一个文件,学生(1)传播,学生14设置为(大概)0。自从我玩这种类型的文件以来,已经有一段时间了,所以YMMV。