2013-03-23 168 views
3

請看代碼。我是初學者,這是我第一次在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 

} 

回答

4

在C++中,您分配內存以這樣的創建緩衝區:

char* buffer = new char[length]; 

與您的代碼的問題是,你使用的()代替[]

當你要釋放這些緩衝區的內存,您可以使用delete[]操作:

delete[] buffer; 

而且,你是正確地從文件中讀取,但不是你所期望的方式。 這是有效的語法和所有,但問題是,你覆蓋緩衝區中的數據。

或許你也應該閱讀這樣的:(其中indexint初始化爲0while循環之前)

readNewFile.read(&ch[index], sizeof(Admin)); 
index = index + sizeof(Admin); 

正如評論用戶建議,你甚至可以用一個std::vector<char>因爲它的速度與char*一樣快,並且不需要特定的尺寸:)

+2

+1爲答案。也就是說,OP應該完全拋出'new/delete',並且只是放大一個'std :: vector <>'。 – WhozCraig 2013-03-23 19:17:55

+0

@ Magtheridon96完成了你所說的修正,但代碼仍然沒有從文件中刪除所需的項目,在我的代碼中寫入和讀取緩衝區時是否有錯誤? – Udit 2013-03-23 19:23:29

+0

嘗試將諸如'pos'和可能的'ch'緩衝區等變量的內容打印到控制檯中。 – 2013-03-23 19:26:50

相關問題