C++ 二进制文件编辑
请帮助我在使用此功能时遇到问题。代码可以编译,但不会更改文件中的任何内容。我很困惑我该做什么。。。。我应该从文件中选择要编辑的记录,然后对其进行更改,我的当前代码允许我进行选择,但当我编辑记录时,不会存储任何内容C++ 二进制文件编辑,c++,file-io,binary,C++,File Io,Binary,请帮助我在使用此功能时遇到问题。代码可以编译,但不会更改文件中的任何内容。我很困惑我该做什么。。。。我应该从文件中选择要编辑的记录,然后对其进行更改,我的当前代码允许我进行选择,但当我编辑记录时,不会存储任何内容 void editRecord(Cookie &type) { fstream dataFile; int num; int count = 0; dataFile.open("/Users/jordanmcpeek/Documents/201
void editRecord(Cookie &type)
{
fstream dataFile;
int num;
int count = 0;
dataFile.open("/Users/jordanmcpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat", ios::in | ios::out | ios::binary);
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
// While not at the end of the file, display the records
while (!dataFile.eof())
{
// Display the records.
cout << endl;
cout << count << ". Description: ";
cout << type.description << endl;
cout << "Quantity Sold: ";
cout << type.quantity << endl;
cout << "Price: $";
cout << type.price << endl;
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
count++;
}
cout << "Which record would you like to edit?: ";
cin >> num;
cout << endl;
cin.ignore();
dataFile.seekp(num * sizeof(type), ios::beg);
cout << "Please enter the new description for the cookie: ";
cin.getline(type.description, SIZE);
cout << endl;
do
{
cout << endl;
cout << "Please enter the new amount sold: ";
cin >> type.quantity;
cin.ignore();
}while(type.quantity < 0);
cout << endl;
do
{
cout << "Please enter the new price: $";
cin >> type.price;
cin.ignore();
}while(type.price < 0);
cout << endl;
// Change the record
dataFile.write(reinterpret_cast<char *>(&type), sizeof(type));
dataFile.close();
}
void editRecord(Cookie和类型)
{
流数据文件;
int-num;
整数计数=0;
打开(“/Users/jordanmpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat”,ios::in | ios::out | ios::binary);
read(reinterpret_cast(&type),sizeof(type));
//不在文件末尾时,显示记录
而(!dataFile.eof())
{
//显示记录。
您是否尝试在调试器中运行此操作?确保文件确实已成功打开?并且写入操作也已成功?您知道如何检查fstream
操作是否失败吗?我知道文件已正确打开,因为我有其他可以工作的函数,如果您确实读取了文件的eof,则此函数会出现问题e将处于错误状态。在期望任何其他操作(如seek)成功之前,您需要清除错误。这就是为什么检查错误很重要的原因。在读取后放置一个数据文件。clear();解决了我的问题。感谢退休的忍者