我想在已存在的文件中的特定位置寫入某些內容,但是我希望在寫入新內容之前擦除舊內容。寫入文件中的特定位置,但先擦除舊內容
例如,假設以下是目標文件的內容。
27013.
Anderson Alston.
22.
9 Hall st.
25/7/2013.
0. << target position here
現在,修改後的文件內容將是
27013.
Anderson Alston.
22.
9 Hall st.
25/7/2013.
190. << this position has been modified
最後,下面是我的代碼,我寫的。
cout << "Amount of deposit: ";
cin >> amount;
ofstream ifile("file.txt", ios::out|ios::trunc);
ifile.seekp(pos); // `pos` is variable that stores the position
ifile << amount << ".";
ifile.close();
你意識到該文件被改變的長度,對不對?您不能輕易*將*插入文本文件中,只需要文件流(需要*移動*以下所有數據)。你最好的選擇是讀入文件,處理它,然後寫回去。 –
@BrianNeal如果你想要,我們可以刪除所有這些註釋:-) –