gpt4 book ai didi

c++ - 代码不适用于 "Modifying a data in a Binary file"

转载 作者:行者123 更新时间:2023-11-28 02:58:15 29 4
gpt4 key购买 nike

所以这是我的“从二进制文件修改记录”的代码,它应该可以工作...

void Update()
{
fstream file;

STUDENT st, temp; // STUDENT is a class which I made

int RollNo;
clrscr();
cout << "Enter the Roll Number: ";
cin >> RollNo; // to get the roll number which is to be modified. Also there is a data member inside the class STUDENT which is also known as RollNo

cout << "\n Enter the update info...\n\n";
st.Input(); // This is a function inside the class STUDENT to get the values for the data members

file.open("Student.dat", ios::binary | ios::ate);
file.seekg(0);

while(file)
{
file.read((char*)&temp, sizeof(temp)); // the data which is being read is stored inside temp

if(temp.retRollNo() == RollNo) // since RollNo is a private data member inside the class STUDENT so I've created an accessor function which returns RollNo
{
file.seekp(file.tellg() - sizeof(temp));
file.write((char*)&st, sizeof(st));
}
} // please note that this loop modifies all the instances which match the criteria and not just one since this while loop runs until end of file

file.close();
}

但是这段代码的问题是它没有修改任何记录...为什么?

最佳答案

您应该在 if(temp.retRollNo() == RollNo) 中添加调试语句,类似于 cout << "Made it here\n";

看完this link我认为你真的应该通过 std::fstream::in | std::fstream::out 作为 file.open() 的第二个参数.

关于c++ - 代码不适用于 "Modifying a data in a Binary file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21507414/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com