此代码应该将一些项目写入文件,但创建的文件有 0 个字节并且是空白的。我不确定是什么问题。
我没有任何错误。此外,随机访问文件可以是 .txt 还是必须是 .dat?
add 函数运行并无错误地添加信息,但文件中没有任何内容。
void add()
{
int hour, min, day, month, yr, snum, interNo,age;
string fname, lname, clinic, area, ex, li, type, sname, town, pay,problem, breed, gender;
char ans;
Intervention inte;
fstream InfoFile("JSPCA.dat", ios::in | ios::out |ios::app);
if (!InfoFile)
{
cout << "Error -file could not be opened.";
}
else
{
cout<<"Enter intervention number\n";
("Enter 0 to end input)\n");
cin>>interNo;
system("cls");
InfoFile.seekp(sizeof(Intervention)*(interNo - 1));
/* read record from file*/
InfoFile.read(reinterpret_cast<char *> (&inte), sizeof(Intervention));
if (inte.getClient().getInterventionNo() != 0)
{
cout << "inter # already contains information.\n";
}
else {
/* create record */
while (interNo != 0) {
InfoFile.seekp(sizeof(Intervention)*(interNo - 1));
InfoFile.read(reinterpret_cast<char *> (&inte), sizeof(Intervention));
if (inte.getClient().getInterventionNo() != 0)
cout << "inter # already contains information.\n";
else {
// user enters information, which is copied into file
cout << "Enter name of clinic(Winchester or Caymanas)\n ";
cin >> clinic;
cout << "Enter lastname, firstname\n ";
cin >> lname;
cin >> fname;
cout << "Please Address(Street#, Street Name, Town)\n";
cin >> snum >> sname >> town;
cout << "Enter Contact#:(area exchange line)\n";
cin >> area >> ex >> li;
cout << "Enter Animal Type\n";
cin >> type;
cout << "Enter Animal Breed\n";
cin >> breed;
cout << "Enter animal's gender\n";
cin >> gender;
cout << "Enter Animal problem\n";
cin >> problem;
cout << "Enter age of animal\n";
cin >> age;
cout << "Please enter letter for payment type:\n";
cout << "Full=F\n";
cout << "Contribution=C\n";
cout << "Can't Pay=CP\n";
cin >> pay;
cout << "Enter date in format dd mm yyyy\n";
cin >> day >> month >> yr;
cout << "Enter the time(hour minute\n)";
cin >> hour >> min;
//inte.getClient().getInterventionNo() == interNo;
// set records for Client, address, TelNo, animal, date and time values
inte.setClient(Client(fname, lname, pay, interNo, clinic));
inte.setAddress(Address(snum, sname, town));
inte.setTelNo(TelNo(area, ex, li));
inte.setAnimal(Animal(type, breed, gender, problem, age));
inte.setDate(Date(day, month, yr));
inte.setTime(Time(hour, min));
InfoFile.seekp(sizeof(Intervention)*(interNo - 1));
InfoFile.write(reinterpret_cast<const char *>(&inte), sizeof(Intervention));
}
system("cls");
cout << "Enter new intervention number\n";
cout<<"Enter 0 to end input";
cin >> interNo;
}
}
}
}