请看一下代码。我是初学者,这是我第一次在 C++ 中创建缓冲区。如何在 C++ 中创建缓冲区以在将旧内容读入该缓冲区并忽略要删除的部分同时截断旧数据并从缓冲区存储内容后创建新文件?
int main() {
Admin item; // Admin is a class
ios::pos_type pos;
int productId;
char *ch; // pointer to create buffer
int length;
cout << "Enter Product Id of item to delete: ";
cin >> productId;
ifstream readFile("Stock.dat", ios::binary | ios:: in | ios::out);
while (readFile) {
readFile.read(reinterpret_cast<char*>(&item), sizeof(Admin));
if (item.getStatus() == productId) {
pos = readFile.tellg() - sizeof(Admin);
break;
}
}
readFile.close();
ifstream readNewFile("Stock.dat", ios::binary | ios:: in | ios::out);
readNewFile.seekg(0, ios::end);
length = readNewFile.tellg();
ch = new char[length]; // is this how buffer is created?if no, please correct it.
readNewFile.seekg(0, ios::beg);
while (readNewFile) {
if (readNewFile.tellg() == pos)
readNewFile.ignore(sizeof(Admin));
readNewFile.read((ch), sizeof(Admin)); // is this how contents are read into buffer from file stream;
if (readNewFile.eof())
readNewFile.close();
}
ofstream outFile("Stock.dat", ios::trunc | ios::app);
outFile.write(ch, sizeof(Admin)); // I am doubtful in this part also
}