請看代碼。我是初學者,這是我第一次在C++中創建緩衝區。如何在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
}
+1爲答案。也就是說,OP應該完全拋出'new/delete',並且只是放大一個'std :: vector <>'。 – WhozCraig 2013-03-23 19:17:55
@ Magtheridon96完成了你所說的修正,但代碼仍然沒有從文件中刪除所需的項目,在我的代碼中寫入和讀取緩衝區時是否有錯誤? – Udit 2013-03-23 19:23:29
嘗試將諸如'pos'和可能的'ch'緩衝區等變量的內容打印到控制檯中。 – 2013-03-23 19:26:50